﻿window.ArthurGraus = window.ArthurGraus || {};

var spoe;

$(document).ready(function () {
    spoe = new ArthurGraus.SharePointFileExplorer();
    spoe.initialize();
});

ArthurGraus.SharePointFileExplorer = function () {
    var mainself = this;
    var mainViewModel = new ViewModel();
    var waitDialog = null;
    mainself.adRotator = null;
//    mainself.adRotator2 = null;

    mainself.analytics = null;


    mainself.Wait = function () {
        waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose(SP.Res.dialogLoading15);
    }
    mainself.CancelWait = function () {
        waitDialog.close();
    }
    mainself.initialize = function () {
        mainself.adRotator = new ArthurGraus.AdRotator('SPFE', 10000, 'adRotator1', 1);
        mainself.adRotator.initialize();

//        mainself.adRotator2 = new ArthurGraus.AdRotator('SPFE', 10000, 'adRotator2', 2);
//        mainself.adRotator2.initialize();

        mainself.analytics = new ArthurGraus.Analytics('SPFE');
        mainself.analytics.initialize();
        
        mainViewModel.initialize();
        ko.applyBindings(mainViewModel);
    }



    function RecycleBin() {
        var self = this;
        self.type = "Recycle";
        self.icon = "../Images/RecycleIcon.png";
        self.imgIntensity = ko.observable("../Images/intensity4.png");
        self.formattedName = ko.computed(function () {
            return "Recycle";
        });
    }

    function searchDirection(searchDirectory) {
        var self = this;
        self.searchDirectory = searchDirectory;
        self.parentFolder = searchDirectory.parentFolder;
        self.folders = ko.observableArray();
        self.files = ko.observableArray();
        self.parent = ko.observableArray();
        self.type = "Search";
        self.icon = ko.observable(searchDirectory.icon());
        self.imgIntensityRight = ko.observable(searchDirectory.imgIntensityRight());
        self.formattedName = ko.computed(function () {
            var finalName = "Search Results in " + self.searchDirectory.formattedName();
            if (finalName.length < 46)
                return finalName;
            else {
                var NewfinalName = finalName.substring(0, 42) + "...";
                return NewfinalName;
            }
        });
    }

    function folder(folder, parent, imgSource,Datemodified,size,path) {
        var self = this;
        self.intensityImgLong = ["../Images/intensity2long.png", "../Images/intensity3long.png", "../Images/intensity4long.png"];
        self.folder = folder;
        self.parentFolder = self.folder;
        self.type = "Folder";
        self.icon = ko.observable("../Images/folder.png");
        self.Datemodified = ko.observable(Datemodified);
        self.size = ko.observable(size);
        self.path = ko.observable(path);
        self.parent = ko.observableArray(parent);
        self.subfolders = ko.observableArray();
        self.files = ko.observableArray();
        self.currentUrl = null;
        self.imgSource = ko.observable(imgSource);
        self.imgIntensity = ko.observable("../Images/intensity4.png");
        self.selected = ko.observable(false);
        self.hovered = ko.observable(false);
        self.opacity = ko.observable(1);
        self.BelongedLibrary = ko.observable();
        self.originalN = ko.computed(function () {
            try {
                var finalName = self.folder.get_name();

                return finalName;
            }
            catch (err) {
                var finalName = self.folder.get_leafName();
                return finalName;

            }
        })

        self.formattedPath = ko.computed(function () {
            try {
                var pathResult = '...' + self.folder.get_serverRelativeUrl();
            }
            catch (err) {
                var pathResult = '...' + self.folder.get_dirName();
            }
            if (pathResult.length < 56)
                return pathResult;
            else {
                var pathResult = pathResult.substring(0, 52) + "...";
                return pathResult;
            }
        })
        self.formattedName = ko.computed(function () {
            try{
                var finalName = self.folder.get_name();
                if (finalName.length < 30)
                    return finalName;
                else {
                    var NewfinalName = finalName.substring(0, 26) + "...";
                    return NewfinalName;
                }
            }
            catch (err) {
                var finalName = self.folder.get_leafName();
                if (finalName.length < 30)
                    return finalName;
                else {
                    var NewfinalName = finalName.substring(0, 26 ) + "...";
                    return NewfinalName;
                }
            }
        });
        self.formattedDate = ko.computed(function () {
            if (self.Datemodified().length < 38)
                return self.Datemodified();
            else {
                var NewfinalDate = self.Datemodified().substring(0, 35) + "...";
                return NewfinalDate;
            }
        });
        self.imgIntensityRight = ko.computed(function () {
            if (self.hovered())
                return self.intensityImgLong[0];
            else if (self.selected())
                return self.intensityImgLong[1];
            else
                return self.intensityImgLong[2];
        });

    }


    
    function file(file, Icon, Datemodified, specificType, size,path) {
        var self = this;
        self.moderationStatus = ko.observable(5);
        self.file = file;
        self.type = "File";
        self.Datemodified = ko.observable(Datemodified);
        self.size = ko.observable(size);
        //self.Version = ko.observable(self.file.get_uiVersionLabel());
        self.specificType = ko.observable(specificType);
        self.path = ko.observable(path);
        self.icon = ko.observable(Icon);
        self.intensityImgLong = ["../Images/intensity2long.png", "../Images/intensity3long.png", "../Images/intensity4long.png"];
        self.imgIntensity = ko.observable("../Images/intensity4.png");
        self.imgIntensityRight = ko.observable("../Images/intensity4long.png");
        self.selected = ko.observable(false);
        self.hovered = ko.observable(false);
        self.opacity = ko.observable(1);
        self.Version = ko.computed(function () {
            try {
                return self.file.get_uiVersionLabel();
            }
            catch (err) {
                return null;
            }
        });
        self.StatusApproval = ko.computed(function () {
            if (self.moderationStatus() == 0) {
                return "Approved";
            }
            else if (self.moderationStatus() == 1) {
                return "Rejected";
            }
            else if (self.moderationStatus() == 2) {
                return "Pending";
            }
            else if (self.moderationStatus() == 3) {
                return "Draft";
            }
            else if (self.moderationStatus() == 4) {
                return "Scheduled";
            }
            else {
                return " ";
            }
        });
        self.iconUrl = ko.computed(function () {
            try{
                return SP.Utilities.Utility.getImageUrl(self.icon().get_value());
            }
            catch (err) {
                return null;
            }
        });
        self.imgIntensityRight = ko.computed(function () {
            if (self.hovered())
                return self.intensityImgLong[0];
            else if (self.selected())
                return self.intensityImgLong[1];
            else
                return self.intensityImgLong[2];
        });
        self.originalN = ko.computed(function () {
            try {
                var finalName = self.file.get_name();

                return finalName;
            }
            catch (err) {
                var finalName = self.file.get_leafName();
                return finalName;

            }


        });
        self.formattedDate = ko.computed(function () {
            if (self.Datemodified().length < 38)
                return self.Datemodified();
            else {
                var NewfinalDate = self.Datemodified().substring(0, 35) + "...";
                return NewfinalDate;
            }
        });
        self.formattedPath = ko.computed(function(){
            try {
                var pathResult = '...' + self.file.get_serverRelativeUrl();
            }
            catch (err) {
                var pathResult = '...' + self.file.get_dirName();
            }
            if (pathResult.length < 56)
                return pathResult;
            else {
                var pathResult = pathResult.substring(0, 52) + "...";
                return pathResult;
            }
        })

        self.normalPath = ko.computed(function () {
            if (self.path() != null) {
                return self.path();
            }
            else {
                return self.file.get_dirName();
            }
        })

        self.formattedName = ko.computed(function () {
            try{
                var finalName = self.file.get_name();
                if (finalName.length < 30)
                    return finalName;
                else {
                    var NewfinalName = finalName.substring(0, 26) + "...";
                    return NewfinalName;
                }
            }
            catch(err){
                var finalName = self.file.get_leafName();
                if (finalName.length < 30)
                    return finalName;
                else {
                    var NewfinalName = finalName.substring(0, 26) + "...";
                    return NewfinalName;
                }
            }
        });

    }

    function itemRecycle(item, icon) {
        var self = this;
        self.intensityImgLong = ["../Images/intensity2long.png", "../Images/intensity3long.png", "../Images/intensity4long.png"];
        self.folder = folder;
        self.parentFolder = self.folder;
        self.type = "Folder";
        self.icon = ko.observable("../Images/folder.png");
        self.Datemodified = ko.observable(Datemodified);
        self.size = ko.observable(size);
        self.path = ko.observable(path);
        self.parent = ko.observableArray(parent);
        self.subfolders = ko.observableArray();
        self.files = ko.observableArray();
        self.currentUrl = null;
        self.imgSource = ko.observable(imgSource);
        self.imgIntensity = ko.observable("../Images/intensity4.png");
        self.selected = ko.observable(false);
        self.hovered = ko.observable(false);
        self.opacity = ko.observable(1);
        self.BelongedLibrary = ko.observable();

        self.formattedName = ko.computed(function () {
            var finalName = self.folder.get_name();
            if (finalName.length < 46)
                return finalName;
            else {
                var NewfinalName = finalName.substring(0, 42) + "...";
                return NewfinalName;
            }
        });
        self.imgIntensityRight = ko.computed(function () {
            if (self.hovered())
                return self.intensityImgLong[0];
            else if (self.selected())
                return self.intensityImgLong[1];
            else
                return self.intensityImgLong[2];
        });

    }

    function Library(libraryItem, imgSource,parent,isHidden) {
        var self = this;
        self.type = "Library";
        self.libraryItem = libraryItem;
        self.parent = ko.observableArray(parent);
        self.icon = ko.observable("../Images/itdl.png");
        self.isHidden = ko.observable(isHidden);
        self.parentFolder = self.libraryItem.get_rootFolder();
        self.subfolders = ko.observableArray();
        self.imgSource = ko.observable(imgSource);
        self.imgIntensity = ko.observable("../Images/intensity4.png");
        self.imgIntensityRight = ko.observable("../Images/intensity4long.png");
        self.formattedName = ko.computed(function () {
            var finalName = "  " + self.libraryItem.get_title();
            return finalName;
        });
    }
    function Site(site, imgSource,icon,parent) {
        var self = this;
        self.type = "Site";
        self.site = site;
        self.icon = ko.observable("../Images/subsite.png");
        self.parent = ko.observableArray(parent);
        self.iconUrl = ko.computed(function () {
            return icon;
        });
        self.parentFolder = self.site.get_rootFolder();
        self.imgSource = ko.observable(imgSource);
        self.imgIntensity = ko.observable("../Images/intensity4.png");
        self.imgIntensityRight = ko.observable("../Images/intensity4long.png");
        self.imgSourcelibrary = ko.observable(imgSource);
        self.imgSourcesubSite = ko.observable(imgSource);
        self.hasUniqueRoleAssignment = ko.observable(false);
        self.collectionCount = 0;
        self.itemCollection = null;
        self.recycleBin = self.site.get_recycleBin();
        self.recycleBinItem = ko.observableArray();
        self.recycleBinPresent = ko.observable(new RecycleBin());
        self.softedItemCollection = new Array();
        self.librarylvl2 = String(self.site.get_id()) + "library2";
        self.subSitelvl2 = String(self.site.get_id()) + "subSite2";
        self.libraries = ko.observableArray();
        self.subSites = ko.observableArray();
        self.formattedName = ko.computed(function () {
            var finalName = "  " + self.site.get_title();
            return finalName;
        });
    }



    function ViewModel() {
        var self = this;
        //var Ref = null;
        var Icon = new Array();
        var currentImg = null;
        var FileDirRef = new Array();
        var item = null;
        var siteName = "";
        var onFolder = false;
        var currentSelection = null;
        var currentLibrary = null;
        var itemsfieldValues = new Array();
        var itemCollection = new Array();
        var folderCollection = new Array();
        var searchfolders = new Array();
        var searchfiles = new Array();
        var searchfoldersitem = new Array();
        var searchfilesitem = new Array();
        var SiteID = null;
        var listSaver = new Array();
        var valueLoading = false;
        var hasPrinciple = true;
        var temporaryObject = null;
        //var camlQuery = new SP.CamlQuery.createAllItemsQuery();
        var camlQuery = new SP.CamlQuery();
        var Itemcount = 0;
        var loadingIcon = false;
        var currentFolder = null;
        var onCopyActive = false;
        var Olddestination = null;
        var newDocument = "";
        var CurrentDesSite = null;
        var orderByNameP = true;
        var orderByApprovalStatusP = true;
        var orderByVersionP = true;
        var orderByDateP = true;
        var orderByTypeP = true;
        var orderByPathP = true;
        var orderBySizeP = true;
        var isPublish = false;
        var isunPublish = false;
        var isApprove = false;
        var isReject = false;
        var findTarget = false;
        var LibraryToReset = null;
        var results = null;
        var countResults = 0;
        var onSearch = false;
        var currentSearch = null;
        var ReCycleItems = new Array();
        var SearchSubsite = true;
        var filesToPuborAp = new Array();
        var approvalStatus = new Array();
        self.onSearchSite = ko.observable(true);
        self.sysLoading = ko.observable(false);
        self.showLibrary = ko.observable(true);
        self.ShowHiddenLibraries = ko.observable(false);
        self.CurrentName = ko.observable("");
        self.hostWebUrl = "";
        self.appWebContext = null;
        self.hostWebContext = null;
        self.hostWeb = null;
        self.itemCollection = null;
        self.temporary = null;
        self.temporary2 = null;
        self.subSiteCollection = null;
        self.redirectListID = null;
        var currentSite = null;
        

        self.imgSource = ["../Images/ArrowHidden.png", "../Images/ArrowShow.png", "../Images/NoArrow.png"];
        self.intensityImg = ["../Images/intensity1.png", "../Images/intensity2.png", "../Images/intensity3.png", "../Images/intensity4.png"];
        self.intensityImgLong = ["../Images/intensity2long.png", "../Images/intensity3long.png", "../Images/intensity4long.png"];
        self.imgCopy = ["../Images/copy.png", "../Images/copyinvi.png", "../Images/copyOnClick.png", "../Images/copyOnHover.png"];
        self.imgCut = ["../Images/cut.png", "../Images/cutinvi.png", "../Images/cutOnClick.png", "../Images/cutOnHover.png"];
        self.imgDelete = ["../Images/Delete1.png", "../Images/Delete1invi.png", "../Images/Delete1OnClick.png", "../Images/Delete1OnHover.png"];
        self.imgPaste = ["../Images/paste.png", "../Images/pasteinvi.png", "../Images/pasteOnClick.png", "../Images/pasteOnHover.png"];
        self.imgRename = ["../Images/rename.png", "../Images/renameinvi.png", "../Images/renameOnClick.png", "../Images/renameOnHover.png"];
        self.imgNewFolder = ["../Images/NewFolder.png", "../Images/NewFolderinvi.png", "../Images/NewFolderOnClick.png", "../Images/NewFolderOnHover.png"];
        self.imgSelectAll = ["../Images/selectAll.png", "../Images/selectAllOnClick.png", "../Images/selectAllOnHover.png"];
        self.imgSelectNone = ["../Images/selectNone.png", "../Images/selectNoneOnClick.png", "../Images/selectNoneOnHover.png"];
        self.BackArrow = ["../Images/arrowUp.png", "../Images/arrowUpHover.png"];
        self.ImgpublishFiles = ["../Images/publish1.png", "../Images/publish2.png", "../Images/publish3.png"];
        self.ImgapproveFiles = ["../Images/approve4.png", "../Images/approve5.png", "../Images/approve6.png"];
        self.ImgunpublishFiles = ["../Images/unpublish1.png", "../Images/unpublish2.png", "../Images/unpublish3.png"];
        self.ImgrejectFiles = ["../Images/RejectApproval4.png", "../Images/RejectApproval5.png", "../Images/RejectApproval6.png"];
        self.ImgcancelapproveFiles = ["../Images/Cancelapprove4.png", "../Images/Cancelapprove5.png", "../Images/Cancelapprove6.png"];
        self.imgInvertSelectionOnClick = ["../Images/invertSelection.png", "../Images/invertSelectionOnClick.png", "../Images/invertSelectionOnHover.png"];
        self.CurrentImgCopy = ko.observable(self.imgCopy[1]);
        self.CurrentImgpublishFiles = ko.observable(self.ImgpublishFiles[1]);
        self.CurrentImgapproveFiles = ko.observable(self.ImgapproveFiles[1]);
        self.CurrentImgunpublishFiles = ko.observable(self.ImgunpublishFiles[1]);
        self.CurrentImgrejectFiles = ko.observable(self.ImgrejectFiles[1]);
        self.CurrentImgcancelapproveFiles = ko.observable(self.ImgcancelapproveFiles[1]);
        self.CurrentImgCut = ko.observable(self.imgCut[1]);
        self.CurrentImgDelete = ko.observable(self.imgDelete[1]);
        self.CurrentImgPaste = ko.observable(self.imgPaste[1]);
        self.CurrentImgRename = ko.observable(self.imgRename[1]);
        self.CurrentImgNewFolder = ko.observable(self.imgNewFolder[1]);
        self.CurrentImgSelectAll = ko.observable(self.imgSelectAll[0]);
        self.CurrentImgSelectNone = ko.observable(self.imgSelectNone[0]);
        self.CurrentImgInvertSelectionOnClick = ko.observable(self.imgInvertSelectionOnClick[0]);
        self.CurrentBackArrow = ko.observable(self.BackArrow[0]);
        self.SearchKeyValue = ko.observable("");
        self.temporaryObject = null;
        self.temporaryPrincipal = null;
        self.siteCollection = ko.observableArray();
        self.folderCollection = ko.observableArray();
        self.fileCollection = ko.observableArray();
        self.CollectionSubsites = ko.observableArray();
        self.CollectionLibraries = ko.observableArray();
        self.currentPosition = ko.observableArray();
        self.currentPositionBeforeSearch = ko.observableArray();
        self.FileToCopy = ko.observableArray();
        self.FolderToCopy = ko.observableArray();
        self.currentLibrary = null;
        self.currentLibraryToCopy = null;
        self.currentLibraryItems = ko.observableArray();
        self.subfolderStrings = ko.observableArray();
        self.isCopy = true;
        self.currentImgControl = ko.observable("../Images/subsite.png");
        self.folderN = "";
        self.initialize = function () {
            camlQuery.set_viewXml('<View Scope=\"RecursiveAll\"><RowLimit>1000</RowLimit></View>')
            self.hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
            self.redirectListID = getQueryStringParameter("List");
            self.appWebContext = new SP.ClientContext.get_current();
            self.hostWebContext = new SP.AppContextSite(self.appWebContext, self.hostWebUrl);
            self.hostWeb = self.hostWebContext.get_web();
            item = self.hostWeb;
            self.appWebContext.load(item);
            self.appWebContext.executeQueryAsync(self.onGetSiteName, self.onError);
            $(document).keydown(function (e) {
                e = e || window.event;
                if (e.keyCode == 27) {
                    self.unCut();
                }
                if (e.keyCode == 13) {
                    if (self.SearchKeyValue().length > 0) {
                        self.onSearchMainSite();
                    }
                }
            });
            var width = $(window).width();
            var height = $(window).height();
            var newheightforData = height - $("#divRibbon").height() - $("#divControlbar").height() - $(".ms-cui-topBar2").height() - $(".ms-core-suiteLink-a").height();
            //$("#divRibbon").width(width);
            $("#cancelApproval").hide();
            $("#divControlbar").width(width);
            $("#Controlbar").width(width - 254);
            var leftP = width - 254 + 40;
            $("#SearchBar").css({ left: leftP + 'px' });
            $("#divData").height(newheightforData);
            $("#Data").height(newheightforData).width(width - $("#divData").width());
            $(window).resize(function () {
                var newwidth = $(window).width();
                var newheight = $(window).height();
                var newheightforData1 = newheight - $("#divRibbon").height() - $("#divControlbar").height() - $(".ms-cui-topBar2").height() - $(".ms-core-suiteLink-a").height();
                //$("#divRibbon").width(newwidth);
                $("#divControlbar").width(newwidth);
                $("#Controlbar").width(newwidth - 254);
                var leftPo = newwidth - 254 + 40;
                $("#SearchBar").css({ left: leftPo + 'px' });
                $("#divData").height(newheightforData1);
                $("#Data").height(newheightforData1).width(newwidth - $("#divData").width());
            });
            SearchSubsite = false;
            $(".SearchMainSite").css({
                "background-image": "url(../Images/SelectHover.png);",
            });
            $(".SearchAllSubsites").css({
                "background-image": "url(../Images/SelectSubSites.png);",
            });

        }

        self.closeAd=function() {
            $("#adCloser").hide();
            $("#adRotator2").hide();
        }

        self.onGetSiteName = function () {
            Icon = [];
            var newIcon = self.appWebContext.get_web().mapToIcon(item.get_title(), '', SP.Utilities.IconSize.Size16);
            self.appWebContext.executeQueryAsync(self.onComplete, self.onError);
            Icon.push(newIcon);
        }

        self.onComplete = function () {
            self.siteCollection.push(new Site(item, self.imgSource[0], Icon[0], new Array()));
            self.appWebContext.load(self.siteCollection()[0].parentFolder);
            self.appWebContext.executeQueryAsync(self.checkForListID,self.onError);
            
        }

        self.checkForListID = function () {
            if (self.redirectListID != null) {
                self.Navigator(self.siteCollection()[0]);
            }
        }

        self.getDirection = function (e) {
            var documentFortest = null;
            self.currentPosition.removeAll();
            for (var number in e.parent()) {
                self.currentPosition.push(e.parent()[number]);
            }
            self.currentPosition.push(e);
            self.currentImgControl(self.currentPosition()[self.currentPosition().length - 1].icon());
            self.CheckButtonNewFolderActivate();
            if (self.FolderToCopy().length > 0 || self.FileToCopy > 0) {
                if(self.currentPosition()[self.currentPosition().length - 1].type=="Site")
                    self.CurrentImgPaste(self.imgPaste[1]);
                else if(!self.checkSameSite(e))
                    self.CurrentImgPaste(self.imgPaste[1]);
                else
                    self.CurrentImgPaste(self.imgPaste[0]);
                
            }


        }

        self.checkSameSite = function (e) {
            var Site1 = null;
            var Site2 = null;
            for (var number in e.parent()) {
                if (e.parent()[number].type == "Site")
                    Site1 = e.parent()[number].site;
            }
            for (var number in CurrentDesSite.parent()) {
                if (CurrentDesSite.parent()[number].type == "Site")
                    Site2 = CurrentDesSite.parent()[number].site;
            }
            if (Site1.get_id().toString() == Site2.get_id().toString())
                return true;
            else
                return false;
        }

        self.CheckButtonNewFolderActivate = function () {
            if (self.currentPosition()[self.currentPosition().length - 1].type == "Folder" || self.currentPosition()[self.currentPosition().length - 1].type == "Library")
                self.CurrentImgNewFolder(self.imgNewFolder[0]);
            else
                self.CurrentImgNewFolder(self.imgNewFolder[1]);
            self.currentLibrary = null;
            for (var num in self.currentPosition()) {
                if (self.currentPosition()[num].type == "Library") {
                    self.currentLibrary = self.currentPosition()[num];
                }
            }
            if (self.currentLibrary != null && self.currentLibrary.isHidden()) {
                self.CurrentImgNewFolder(self.imgNewFolder[1]);
            }
        }


        self.CheckButtonsActivate = function () {
            var num = 0;
            var foldernum = 0;
            var filenum = 0;
            for (var number in self.folderCollection()) {
                if (self.folderCollection()[number].selected())
                    foldernum++;
            }
            for (var number in self.fileCollection()) {
                if (self.fileCollection()[number].selected())
                    filenum++;
            }
            num=foldernum+filenum;
            if (num > 0) {
                self.CurrentImgCopy(self.imgCopy[0]);
                self.CurrentImgCut(self.imgCut[0]);
                self.CurrentImgDelete(self.imgDelete[0]);
                //self.CurrentImgf(self.imgPaste[0]);
                self.CurrentImgRename(self.imgRename[0]);
            }
            else {
                self.CurrentImgCopy(self.imgCopy[1]);
                self.CurrentImgCut(self.imgCut[1]);
                self.CurrentImgDelete(self.imgDelete[1]);
                //self.CurrentImgPaste(self.imgPaste[1]);
                self.CurrentImgRename(self.imgRename[1]);
            }


            self.currentLibrary = null;
            var allowPublish = false;
            var allowApprove = false;
            for (var num in self.currentPosition()) {
                if (self.currentPosition()[num].type == "Library") {
                    self.currentLibrary = self.currentPosition()[num];
                    if (self.currentLibrary.libraryItem.get_enableVersioning() && self.currentLibrary.libraryItem.get_enableMinorVersions())
                        allowPublish = true;
                    if (self.currentLibrary.libraryItem.get_enableModeration())
                        allowApprove = true;
                }
            }
            if (self.currentLibrary != null && self.currentLibrary.isHidden()) {
                self.CurrentImgCut(self.imgCut[1]);
                self.CurrentImgDelete(self.imgDelete[1]);
                self.CurrentImgRename(self.imgRename[1]);
            }
            
            
            self.CurrentImgpublishFiles(self.ImgpublishFiles[1]);
            self.CurrentImgapproveFiles(self.ImgapproveFiles[1]);
            self.CurrentImgunpublishFiles(self.ImgunpublishFiles[1]);
            self.CurrentImgrejectFiles(self.ImgrejectFiles[1]);
            self.CurrentImgcancelapproveFiles(self.ImgcancelapproveFiles[1]);
            if ((foldernum > 0 || filenum > 1)) {
                if (allowPublish) {
                    self.CurrentImgpublishFiles(self.ImgpublishFiles[0]);
                    self.CurrentImgunpublishFiles(self.ImgunpublishFiles[0]);
                }
                if (allowApprove) {
                    self.CurrentImgapproveFiles(self.ImgapproveFiles[0]);
                    self.CurrentImgrejectFiles(self.ImgrejectFiles[0]);
                }
                if(allowPublish&&allowApprove)
                    self.CurrentImgcancelapproveFiles(self.ImgcancelapproveFiles[0]);
            }
            else {
                for (var number in self.fileCollection()) {
                    if (self.fileCollection()[number].selected()) {
                        if (self.fileCollection()[number].file.get_level() == 2 && allowPublish && self.fileCollection()[number].StatusApproval() != "Pending") {
                            self.CurrentImgpublishFiles(self.ImgpublishFiles[0]);

                        }
                        if (self.fileCollection()[number].file.get_level() == 1 && allowPublish && self.fileCollection()[number].StatusApproval() != "Pending") {
                            self.CurrentImgunpublishFiles(self.ImgunpublishFiles[0]);
                        }
                        if (allowApprove && self.fileCollection()[number].StatusApproval() != "Approved" && self.fileCollection()[number].StatusApproval() != "Draft" && self.fileCollection()[number].StatusApproval() != "Rejected") {
                            self.CurrentImgapproveFiles(self.ImgapproveFiles[0]);
                            self.CurrentImgrejectFiles(self.ImgrejectFiles[0]);
                        }
                        if (allowApprove && allowPublish && self.fileCollection()[number].StatusApproval() != "Draft" && allowPublish) {
                            self.CurrentImgcancelapproveFiles(self.ImgcancelapproveFiles[0]);
                        }

                    }

                }
            }
            self.CheckPasteActivate();
        }


        self.CheckPasteActivate = function () {
            var num = 0;
            for (var number in self.FolderToCopy()) {
                num++;
            }
            for (var number in self.FileToCopy()) {
                num++;
            }
            if (num > 0) {
                self.CurrentImgPaste(self.imgPaste[0]);
            }
            else {
                self.CurrentImgPaste(self.imgPaste[1]);
            }
            self.currentLibrary = null;
            for (var num in self.currentPosition()) {
                if (self.currentPosition()[num].type == "Library") {
                    self.currentLibrary = self.currentPosition()[num];
                }
            }
            if (self.currentLibrary != null && self.currentLibrary.isHidden()) {
                self.CurrentImgPaste(self.imgPaste[1]);
            }
        }

        self.backOneLvl = function () {
            if (self.currentPosition().length > 1) {
                self.onRedirect(self.currentPosition()[self.currentPosition().length - 2]);
            }
        }
        
        self.onReSelectIntensity = function (site,target) {
            //self.onClearIntensity(site);
            //var finalDes = null;
            try{
                if (site.parentFolder.get_serverRelativeUrl() == target.parentFolder.get_serverRelativeUrl()) {
                    site.imgIntensity(self.intensityImg[1]);
                    findTarget = true;
                }
                for (var count in site.libraries()) {
                    if (site.libraries()[count].parentFolder.get_serverRelativeUrl() == target.parentFolder.get_serverRelativeUrl()) {
                        site.libraries()[count].imgIntensity(self.intensityImg[1]);
                        findTarget= true;
                    }
                    for (var count1 in site.libraries()[count].subfolders()) {
                        self.onReSelectIntensitySubfolder(site.libraries()[count].subfolders()[count1], target);
                    }
                }
                for (var count in site.subSites()) {
                    if (site.subSites()[count].parentFolder.get_serverRelativeUrl() == target.parentFolder.get_serverRelativeUrl()) {
                        site.subSites()[count].imgIntensity(self.intensityImg[1]);
                        findTarget= true;
                    }
                    self.onReSelectIntensity(site.subSites()[count],target);
                }
            }
            catch (err) {
                findTarget = true;
            }

        }

        self.onReSelectIntensitySubfolder = function (folder,target) {
            if (folder.parentFolder.get_serverRelativeUrl() == target.parentFolder.get_serverRelativeUrl()) {
                folder.imgIntensity(self.intensityImg[1]);
                findTarget= true;
            }
            for (var count in folder.subfolders()) {
                self.onReSelectIntensitySubfolder(folder.subfolders()[count],target);
            }
        }

        self.onClearIntensity = function (site) {
            site.imgIntensity(self.intensityImg[3]);
            site.recycleBinPresent().imgIntensity(self.intensityImg[3]);
            for (var count in site.libraries()) {
                site.libraries()[count].imgIntensity(self.intensityImg[3]);
                for (var count1 in site.libraries()[count].subfolders()) {
                    self.onClearIntensitySubfolder(site.libraries()[count].subfolders()[count1]);
                }
            }
            for (var count in site.subSites()) {
                site.subSites()[count].imgIntensity(self.intensityImg[3]);
                site.subSites()[count].recycleBinPresent().imgIntensity(self.intensityImg[3]);
                self.onClearIntensity(site.subSites()[count]);
            }
        }
        self.onClearIntensitySubfolder = function (folder) {
            folder.imgIntensity(self.intensityImg[3]);
            for (var count in folder.subfolders()) {
                self.onClearIntensitySubfolder(folder.subfolders()[count]);
            }
        }

        self.checkImg = function () {
            self.onChangeIntensity(self.siteCollection()[0]);
        }

        self.onChangeIntensity = function (site) {
            if (site.imgIntensity() == self.intensityImg[2])
                site.imgIntensity(self.intensityImg[3]);
            for (var count in site.libraries()) {
                if (site.libraries()[count].imgIntensity() == self.intensityImg[2])
                    site.libraries()[count].imgIntensity(self.intensityImg[3]);
                for (var count1 in site.libraries()[count].subfolders()) {
                    self.onChangeIntensitySubfolder(site.libraries()[count].subfolders()[count1]);
                }
            }
            for (var count in site.subSites()) {
                self.onChangeIntensity(site.subSites()[count]);
            }
        }
        self.onChangeIntensitySubfolder = function (folder) {
            if (folder.imgIntensity() == self.intensityImg[2])
                folder.imgIntensity(self.intensityImg[3]);
            for (var count in folder.subfolders()) {
                self.onChangeIntensitySubfolder(folder.subfolders()[count]);
            }
        }

        self.enableImg = function (e) {
            currentImg = e.imgIntensity();
            e.imgIntensity(self.intensityImg[1]);
        }
        self.disableImg = function (e) {
            e.imgIntensity(currentImg);
        }
        self.enableImgRecy = function (e) {
            currentImg = e.recycleBinPresent().imgIntensity();
            e.recycleBinPresent().imgIntensity(self.intensityImg[1]);
        }
        self.disableImgRecy = function (e) {
            e.recycleBinPresent().imgIntensity(currentImg);
        }

        self.enableCopyImg = function () {
            if (self.CurrentImgCopy() != self.imgCopy[1])
                self.CurrentImgCopy(self.imgCopy[3]);
        }
        self.disableCopyImg = function () {
            if (self.CurrentImgCopy() != self.imgCopy[1])
                self.CurrentImgCopy(self.imgCopy[0]);
        }

        self.enablepublishFilesImg = function () {
            if (self.CurrentImgpublishFiles() != self.ImgpublishFiles[1])
                self.CurrentImgpublishFiles(self.ImgpublishFiles[2]);
        }
        self.disablepublishFilesImg = function () {
            if (self.CurrentImgpublishFiles() != self.ImgpublishFiles[1])
                self.CurrentImgpublishFiles(self.ImgpublishFiles[0]);
        }

        self.enableunpublishFilesImg = function () {
            if (self.CurrentImgunpublishFiles() != self.ImgunpublishFiles[1])
                self.CurrentImgunpublishFiles(self.ImgunpublishFiles[2]);
        }
        self.disableunpublishFilesImg = function () {
            if (self.CurrentImgunpublishFiles() != self.ImgunpublishFiles[1])
                self.CurrentImgunpublishFiles(self.ImgunpublishFiles[0]);
        }

        self.enableapproveFilesImg = function () {
            if (self.CurrentImgapproveFiles() != self.ImgapproveFiles[1])
                self.CurrentImgapproveFiles(self.ImgapproveFiles[2]);
        }
        self.disableapproveFilesImg = function () {
            if (self.CurrentImgapproveFiles() != self.ImgapproveFiles[1])
                self.CurrentImgapproveFiles(self.ImgapproveFiles[0]);
        }

        self.enablerejectFilesImg = function () {
            if (self.CurrentImgrejectFiles() != self.ImgrejectFiles[1])
                self.CurrentImgrejectFiles(self.ImgrejectFiles[2]);
        }
        self.disablerejectFilesImg = function () {
            if (self.CurrentImgrejectFiles() != self.ImgrejectFiles[1])
                self.CurrentImgrejectFiles(self.ImgrejectFiles[0]);
        }

        self.enablecancelapproveFilesImg = function () {
            if (self.CurrentImgcancelapproveFiles() != self.ImgcancelapproveFiles[1])
                self.CurrentImgcancelapproveFiles(self.ImgcancelapproveFiles[2]);
        }
        self.disablecancelapproveFilesImg = function () {
            if (self.CurrentImgcancelapproveFiles() != self.ImgcancelapproveFiles[1])
                self.CurrentImgcancelapproveFiles(self.ImgcancelapproveFiles[0]);
        }

        self.enableArrowImg = function () {
            self.CurrentBackArrow(self.BackArrow[1]);
        }
        self.disableArrowImg = function () {
            self.CurrentBackArrow(self.BackArrow[0]);
        }

        self.enablePasteImg = function () {
            if (self.CurrentImgPaste() != self.imgPaste[1])
                self.CurrentImgPaste(self.imgPaste[3]);
        }
        self.disablePasteImg = function () {
            if (self.CurrentImgPaste() != self.imgPaste[1])
                self.CurrentImgPaste(self.imgPaste[0]);
        }

        self.enableCutImg = function () {
            if (self.CurrentImgCut() != self.imgCut[1])
                self.CurrentImgCut(self.imgCut[3]);
        }
        self.disableCutImg = function () {
            if (self.CurrentImgCut() != self.imgCut[1])
                self.CurrentImgCut(self.imgCut[0]);
        }

        self.enableDeleteImg = function () {
            if (self.CurrentImgDelete() != self.imgDelete[1])
                self.CurrentImgDelete(self.imgDelete[3]);
        }
        self.disableDeleteImg = function () {
            if (self.CurrentImgDelete() != self.imgDelete[1])
                self.CurrentImgDelete(self.imgDelete[0]);
        }

        self.enableRenameImg = function () {
            if (self.CurrentImgRename() != self.imgRename[1])
                self.CurrentImgRename(self.imgRename[3]);
        }
        self.disableRenameImg = function () {
            if (self.CurrentImgRename() != self.imgRename[1])
                self.CurrentImgRename(self.imgRename[0]);
        }

        self.enableNewFolderImg = function () {
            if (self.CurrentImgNewFolder() != self.imgNewFolder[1])
                self.CurrentImgNewFolder(self.imgNewFolder[3]);
        }
        self.disableNewFolderImg = function () {
            if (self.CurrentImgNewFolder() != self.imgNewFolder[1])
                self.CurrentImgNewFolder(self.imgNewFolder[0]);
        }

        self.enableInvertImg = function () {
            self.CurrentImgInvertSelectionOnClick(self.imgInvertSelectionOnClick[2]);
        }
        self.disableInvertImg = function () {
            self.CurrentImgInvertSelectionOnClick(self.imgInvertSelectionOnClick[0]);
        }

        self.enableSelectNoneImg = function () {
            self.CurrentImgSelectNone(self.imgSelectNone[2]);
        }
        self.disableSelectNoneImg = function () {
            self.CurrentImgSelectNone(self.imgSelectNone[0]);
        }

        self.enableSelectAllImg = function () {
            self.CurrentImgSelectAll(self.imgSelectAll[2]);
        }
        self.disableSelectAllImg = function () {
            self.CurrentImgSelectAll(self.imgSelectAll[0]);
        }

        self.enableImgLong = function (e) {
            if (e.type == "Folder" || e.type == 'File') {
                e.hovered(true);
            }
            else {
                currentImg = e.imgIntensity();
                e.imgIntensityRight(self.intensityImgLong[0]);
            }
        }
        self.disableImgLong = function (e) {
            if (e.type == "Folder" || e.type == 'File') {
                e.hovered(false);
            }
            else {
                e.imgIntensityRight(currentImg);
            }
        }

        self.checkIntensityLibraryItems = function (e) {
            if(e.checked)
                e.imgIntensityRight(self.intensityImgLong[1]);
            else
                e.imgIntensityRight(self.intensityImgLong[1]);
        }
        self.checkforTarget = function () {
            findTarget = false;
            num = self.currentPosition().length;
            while (!findTarget) {
                num -= 1;
                self.onReSelectIntensity(self.siteCollection()[0],self.currentPosition()[num]);
            }
        }

        self.ShowLibraryDatabyClick = function (e) {
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.onHidePath();
            self.onClearIntensity(self.siteCollection()[0]);
            e.imgIntensity(self.intensityImg[2]);
            currentImg = self.intensityImg[2];
            e.subfolders.removeAll();
            if (!onCopyActive) {
                self.getDirection(e);
                self.checkforTarget();
                self.folderCollection.removeAll();
                self.fileCollection.removeAll();
                self.CollectionLibraries.removeAll();
                self.CollectionSubsites.removeAll();
                self.CheckButtonsActivate();
            }
            mainself.Wait();
            currentSelection = e;
            for (var num in self.currentPosition()) {
                if (self.currentPosition()[num].type == "Library") {
                    self.currentLibrary = self.currentPosition()[num];
                }
            }
            self.loadSubFoldersandFiles();

        }

        self.ShowLibraryData = function (e) {
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.onHidePath();
            self.onClearIntensity(self.siteCollection()[0]);
            e.imgIntensity(self.intensityImg[2]);
            currentImg = self.intensityImg[2];
            self.getDirection(e);
            self.checkforTarget();
            e.subfolders.removeAll();
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            self.CollectionLibraries.removeAll();
            self.CollectionSubsites.removeAll();
            self.CheckButtonsActivate();
            mainself.Wait();
            currentSelection = e;
            for (var num in self.currentPosition()) {
                if (self.currentPosition()[num].type == "Library") {
                    self.currentLibrary = self.currentPosition()[num];
                }
            }
            self.loadSubFoldersandFiles();
            /*if (e.imgSource() == self.imgSource[0] || e.imgSource() == self.imgSource[2]) {
                if (e.imgSource() != self.imgSource[2]) {
                    e.imgSource(self.imgSource[1]);
                }


                
            }
            else {
                if (e.imgSource() != self.imgSource[2]) {
                    e.imgSource(self.imgSource[0]);
                }
            }*/

        }

        self.onRedirect = function (e) {
            self.onClearIntensity(self.siteCollection()[0]);
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            if (e.type == "Folder") {
                self.showFolderDatabyClick(e);
            }
            else if (e.type == "Site") {
                self.NavigatorDirect(e);
            }
            else if (e.type == "Search") {
                self.ShowSearchResults(e);
            }
            else if (e.type == "Recycle") {
                self.LoadReCycleBin(currentSelection);
            }
            else {
                self.ShowLibraryDatabyClick(e);
            }
        }

        self.ShowSearchResults = function (e) {
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            self.CollectionLibraries.removeAll();
            self.CollectionSubsites.removeAll();
            for (var num in e.folders()) {
                self.folderCollection.push(e.folders()[num]);
            }
            for (var num in e.files()) {
                self.fileCollection.push(e.files()[num]);
            }
        }

        self.addCheckedFile = function (e, event) {
            if(!event.ctrlKey)
                self.doselectNone();
            //self.FileToCopy = e;
            if (e.selected()) {
                e.selected(false);
            }
            else {
                e.selected(true);
            }
            self.CheckButtonsActivate();
        }

        self.CopyFileToDestination = function () {
            if(self.CurrentImgPaste()==self.imgPaste[3]){
                mainself.Wait();
                var num = 0;
                for (var number in self.FileToCopy()) {
                    self.onFileCopy(self.currentPosition()[self.currentPosition().length - 1], self.FileToCopy()[number].file);
                }
                for (var number in self.FolderToCopy()) {
                    num++;
                }
                if (num > 0) {
                    self.itemCollection = self.currentLibraryToCopy.libraryItem.getItems(camlQuery);
                    self.appWebContext.load(self.itemCollection);
                    self.appWebContext.executeQueryAsync(self.onLoadLibraryFiles, self.onError);
                }
                else {
                    onCopyActive = true;
                    self.appWebContext.executeQueryAsync(self.done, self.onError);
                }
            }
        }

        self.onLoadLibraryFiles = function () {
            self.currentLibraryItems.removeAll();
            self.subfolderStrings.removeAll();
            self.CheckButtonsActivate();
            var itemEnumerator = self.itemCollection.getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.currentLibraryItems.push(itemEnumerator.get_current());
            }
            for (var num in self.currentLibraryItems()) {
                if (self.currentLibraryItems()[num].get_fileSystemObjectType() == 0) {
                    //var FileNew = self.currentLibraryItems()[num].get_file();
                    self.appWebContext.load(self.currentLibraryItems()[num], "File");
                }
            }
            self.appWebContext.executeQueryAsync(self.onLoadLibrary, self.onError);
        }

        self.onLoadReclycleBine = function () {

        }

        self.onLoadLibrary = function () {
            var subfoldersAl = new Array();
            
            /*var itemEnumerator = self.itemCollection.getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.currentLibraryItems.push(itemEnumerator.get_current());
            }*/
            for (var number in self.FolderToCopy()) {
                var NewSubfolderArray = new Array();
                NewSubfolderArray.push(self.FolderToCopy()[number].folder.get_name());
                var FileRef = self.FolderToCopy()[number].folder.get_serverRelativeUrl();
                FileRef = FileRef.substring(0, FileRef.length - self.FolderToCopy()[number].folder.get_name().length);
                FileRef += self.FolderToCopy()[number].folder.get_name();
                self.onFolderCopy2(FileRef, NewSubfolderArray);
            }
            //self.subfolderStrings()[0][0] = self.onCheckUniqueNameFolder(self.subfolderStrings()[0][0]);
            for (var num in self.subfolderStrings()) {
                var subArray = new Array();
                for (var count in self.subfolderStrings()[num]) {
                    subArray.push(self.subfolderStrings()[num][count]);
                }
                subfoldersAl.push(subArray);
            }
            for (var num in self.subfolderStrings()) {
                self.subfolderStrings()[num][0] = self.onCheckUniqueNameFolder(self.subfolderStrings()[num][0]);
            }
            var Destination = null;
            Destination = self.currentPosition()[self.currentPosition().length - 1].parentFolder.get_serverRelativeUrl();

            for (var number in self.subfolderStrings()) {
                var makeSubfolder = self.currentPosition()[self.currentPosition().length - 1].parentFolder;
                for (var num in self.subfolderStrings()[number]) {
                    makeSubfolder = makeSubfolder.get_folders().add(self.subfolderStrings()[number][num]);

                }
                self.appWebContext.executeQueryAsync();
            }
            for (var number in self.subfolderStrings()) {
                var CurrentDestination = "";
                var CurrentOldDestination = "";
                CurrentOldDestination += Olddestination;
                CurrentDestination += Destination;
                for (var num in self.subfolderStrings()[number]) {
                    CurrentDestination += "/"+self.subfolderStrings()[number][num];
                    CurrentOldDestination += "/" + subfoldersAl[number][num];
                    for (var num in self.currentLibraryItems()) {
                        var CurrentFileRef="";
                        CurrentFileRef+=CurrentOldDestination+"/"+self.currentLibraryItems()[num].get_fieldValues().FileLeafRef;
                        if (self.currentLibraryItems()[num].get_fieldValues().FileRef == CurrentFileRef && self.currentLibraryItems()[num].get_fileSystemObjectType() == 0) {
                            //var FileNew = self.currentLibraryItems()[num].get_file();
                            //self.appWebContext.load(self.currentLibraryItems()[num],"File");
                            self.onFileCopyByUrl(CurrentDestination, self.currentLibraryItems()[num].get_file());
                        }
                    }
                }
                
            }
            self.appWebContext.executeQueryAsync(self.onDeleteFolders, self.onError);
        }

        self.onDeleteFolders = function () {
            if(!self.isCopy){
                for (var number in self.FolderToCopy()) {
                    self.FolderToCopy()[number].folder.recycle();
                }
            }
            onCopyActive = true;
            self.appWebContext.executeQueryAsync(self.done, self.onError);
        }

        self.onFolderCopy2 = function (FileDirRef, Folder) {
            var NewSubfolderArray = new Array();
            var countCheck = 0;
            for (var num in Folder) {
                NewSubfolderArray.push(Folder[num]);
            }
            for (var num in self.currentLibraryItems()) {
                if (self.currentLibraryItems()[num].get_fieldValues().FileDirRef == FileDirRef && self.currentLibraryItems()[num].get_fileSystemObjectType()==1) {
                    NewSubfolderArray.push(self.currentLibraryItems()[num].get_fieldValues().FileLeafRef);
                    var FileRef = self.currentLibraryItems()[num].get_fieldValues().FileRef;
                    self.onFolderCopy2(FileRef, NewSubfolderArray);
                    NewSubfolderArray.pop();
                    countCheck++;
                }
            }
            if (countCheck == 0)
                self.subfolderStrings.push(NewSubfolderArray);

        }


        self.onCopytoNewDestination = function ( Folder) {
            var itemEnumerator = Folder.parentFolder.get_files().getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.onFileCopy(Folder.currentUrl, itemEnumerator.get_current());   
            }
            self.appWebContext.executeQueryAsync();
        }

        self.onFileCopyByUrl = function (Destination, File) {
            var _destinationlibUrl = Destination + '/' + File.get_name();
            File.copyTo(_destinationlibUrl, true);
        }

        self.onCheckUniqueNameFile = function (Name) {
            var fileNames = new Array();
            var newFileName = null;
            for (var num in self.fileCollection()) {
                fileNames.push(self.fileCollection()[num].file.get_name());
            }
            for (var num in fileNames) {
                if (Name == fileNames[num]) {
                    newFileName = fileNames[num];
                    var array = newFileName.split('.');
                    newFileName = array[0] + " - Copy"+"."+array[1];
                    return self.onCheckUniqueNameFile(newFileName);
                }
            }
            if (newFileName == null)
                return Name;
        }

        self.onCheckUniqueNameFolder = function (Name) {
            var folderNames = new Array();
            var newName = null;
            for (var num in self.folderCollection()) {
                folderNames.push(self.folderCollection()[num].folder.get_name());
            }
            for (var num in folderNames) {
                if (Name == folderNames[num]) {
                    newName = folderNames[num] + " - Copy";
                    return self.onCheckUniqueNameFolder(newName);
                }
            }
            if (newName == null)
                return Name;
        }

        self.onFileCopy = function (Destination, File) {
            try {

                if (Destination.type == "Library" && self.isCopy) {

                    var _destinationlibUrl = Destination.parentFolder.get_serverRelativeUrl() + '/' + self.onCheckUniqueNameFile(File.get_name());
                    File.copyTo(_destinationlibUrl, true);
                }
                else if (Destination.type == "Library") {
                    var _destinationlibUrl = Destination.parentFolder.get_serverRelativeUrl() + '/' + self.onCheckUniqueNameFile(File.get_name());
                    File.copyTo(_destinationlibUrl, true);
                    File.recycle();
                }
                else if (Destination.type == "Folder" && !self.isCopy) {
                    var _destinationlibUrl = Destination.folder.get_serverRelativeUrl() + '/' + self.onCheckUniqueNameFile(File.get_name());
                    File.copyTo(_destinationlibUrl, true);
                    File.recycle();

                }
                else if (Destination.type == "Folder" && self.isCopy) {
                    var _destinationlibUrl = Destination.folder.get_serverRelativeUrl() + '/' + self.onCheckUniqueNameFile(File.get_name());
                    File.copyTo(_destinationlibUrl, true);
                }
                if (Destination.type == 'Folder')
                    Destination.folder.update();
                else
                    Destination.libraryItem.update();
            }
            catch (err) {
                var _destinationlibUrl = Destination + '/' + self.onCheckUniqueNameFile(File.get_name());
                File.copyTo(_destinationlibUrl, true);
            }

        }

        self.onCancelSearch = function () {
            $("#divSearchRibbon").hide();
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.currentPosition.removeAll();
            for (var num in self.currentPositionBeforeSearch()) {
                self.currentPosition.push(self.currentPositionBeforeSearch()[num]);
            }
            self.onRedirect(self.currentPosition()[self.currentPosition().length - 1]);
        }

        self.onSearchMainSite = function () {
            SearchSubsite = false;
            $(".SearchMainSite").css({
                "background-image": "url(../Images/SelectHover.png);",
            });
            $(".SearchAllSubsites").css({
                "background-image": "url(../Images/SelectSubSites.png);",
            });
            self.onSearch();
        }

        self.onSearchAllSubsites = function () {
            SearchSubsite = true;
            $(".SearchMainSite").css({
                "background-image": "url(../Images/SelectSubSites.png);",
            });
            $(".SearchAllSubsites").css({
                "background-image": "url(../Images/SelectHover.png);",
            });
            self.onSearch();
        }
        self.onHoverAllSubsites = function () {
            $(".SearchAllSubsites").css({
                "background-image": "url(../Images/SelectHover.png);",
            });
        }
        self.onHoverMainSite = function () {
            $(".SearchMainSite").css({
                "background-image": "url(../Images/SelectHover.png);",
            });
        }
        self.onOffHover = function () {
            if (SearchSubsite) {
                $(".SearchMainSite").css({
                    "background-image": "url(../Images/SelectSubSites.png);",
                });
                $(".SearchAllSubsites").css({
                    "background-image": "url(../Images/SelectHover.png);",
                });
            }
            else {
                $(".SearchMainSite").css({
                    "background-image": "url(../Images/SelectHover.png);",
                });
                $(".SearchAllSubsites").css({
                    "background-image": "url(../Images/SelectSubSites.png);",
                });
            }
        }

        self.doCopy = function () {
            if (self.CurrentImgCopy() == self.imgCopy[3]) {
                self.isCopy = true;
                self.FileToCopy.removeAll();
                for (var num in self.fileCollection()) {
                    self.fileCollection()[num].opacity(1);
                    if (self.fileCollection()[num].selected()) {
                        self.FileToCopy.push(self.fileCollection()[num]);
                    }
                }
                self.FolderToCopy.removeAll();
                for (var num in self.folderCollection()) {
                    self.folderCollection()[num].opacity(1);
                    if (self.folderCollection()[num].selected()) {
                        self.FolderToCopy.push(self.folderCollection()[num]);
                    }
                }
                self.currentLibraryToCopy = null;
                for (var num in self.currentPosition()) {
                    if (self.currentPosition()[num].type == "Library") {
                        self.currentLibraryToCopy = self.currentPosition()[num];
                    }
                }
                self.onSetDestination();
                self.CheckPasteActivate();
            }
        }
        self.onSetDestination = function () {
            Olddestination = self.currentPosition()[self.currentPosition().length - 1].parentFolder.get_serverRelativeUrl();
            CurrentDesSite = self.currentPosition()[self.currentPosition().length - 1];
        }
        self.unCut = function () {
            for (var num in self.fileCollection()) {
                self.fileCollection()[num].opacity(1);
            }
            for (var num in self.folderCollection()) {
                self.folderCollection()[num].opacity(1);
            }
        }
        self.doCut = function () {
            if (self.CurrentImgCut() == self.imgCut[3]) {
                self.isCopy = false;
                self.FileToCopy.removeAll();
                for (var num in self.fileCollection()) {
                    self.fileCollection()[num].opacity(1);
                    if (self.fileCollection()[num].selected()) {
                        self.FileToCopy.push(self.fileCollection()[num]);
                        self.fileCollection()[num].opacity(0.4);
                    }
                }
                self.FolderToCopy.removeAll();
                for (var num in self.folderCollection()) {
                    self.folderCollection()[num].opacity(1);
                    if (self.folderCollection()[num].selected()) {
                        self.FolderToCopy.push(self.folderCollection()[num]);
                        self.folderCollection()[num].opacity(0.4);
                    }
                }
                self.currentLibraryToCopy = null;
                for (var num in self.currentPosition()) {
                    if (self.currentPosition()[num].type == "Library") {
                        self.currentLibraryToCopy = self.currentPosition()[num];
                    }
                }
                self.CheckPasteActivate();
                self.onSetDestination();
            }
        }

        self.doDelete = function () {
            $("#GB_window_Delete").hide();
            mainself.Wait();
            for (var num in self.fileCollection()) {
                if (self.fileCollection()[num].selected()) {
                    self.fileCollection()[num].file.recycle();
                }
            }
            for (var num in self.folderCollection()) {
                if (self.folderCollection()[num].selected()) {
                    self.folderCollection()[num].folder.recycle();
                }
            }
            onCopyActive = true;
            self.appWebContext.executeQueryAsync(self.done, self.onError);

        }
        
        self.onCreateNewFolder = function () {
            if (self.CurrentImgNewFolder() != self.imgNewFolder[1]) {
                $("#GB_window_Rename").hide();
                $("#GB_window_Delete").hide();
                self.CurrentName("New Folder");
                $("#GB_window").show();
            }

        }

        self.createNewFolder = function () {
            var newFolder = self.CurrentName();

            if (newFolder.length>0) {
                self.doNewFolder(self.currentPosition()[self.currentPosition().length - 1].parentFolder,newFolder);
            }
            $("#GB_window").hide();
        }

        self.onRename = function () {
            if (self.CurrentImgRename() == self.imgRename[3]) {
                $("#GB_window").hide();
                $("#GB_window_Rename").hide();
                $("#GB_window_Delete").hide();
                self.CurrentName("");
                var CurrentDocumentName = null;
                var numSelected = 0;
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        numSelected++;
                        CurrentDocumentName = self.folderCollection()[num].formattedName();
                    }
                }
                for (var num in self.fileCollection()) {
                    if (self.fileCollection()[num].selected()) {
                        numSelected++;
                        CurrentDocumentName = self.fileCollection()[num].file.get_title();
                    }
                }

                if (numSelected > 1)
                    alert("You can only rename 1 file or folder at a time");
                else if (numSelected == 0) {
                }

                else {
                    self.CurrentName(CurrentDocumentName);
                    $("#GB_window_Rename").show();
                }
            }
            
        }

        self.onDelete = function () {
            if (self.CurrentImgDelete() == self.imgDelete[3]) {
                $("#GB_window").hide();
                $("#GB_window_Rename").hide();
                $("#GB_window_Delete").show();
            }

        }

        self.onOktoRename = function () {
            var numSelected = 0;
            for (var num in self.folderCollection()) {
                if (self.folderCollection()[num].selected()) {
                    numSelected++;
                }
            }
            for (var num in self.fileCollection()) {
                if (self.fileCollection()[num].selected()) {
                    numSelected++;
                }
            }

            if (numSelected > 1)
                alert("You can only rename 1 document at a time");
            else if (numSelected == 0) {
            }
            else {
                newDocument = self.CurrentName();

                if (newDocument.length>0) {
                    self.currentLibraryToCopy = null;
                    for (var num in self.currentPosition()) {
                        if (self.currentPosition()[num].type == "Library") {
                            self.currentLibraryToCopy = self.currentPosition()[num];
                        }
                    }
                    self.itemCollection = self.currentLibraryToCopy.libraryItem.getItems(camlQuery);
                    self.appWebContext.load(self.itemCollection);
                    self.appWebContext.executeQueryAsync(self.doRenameFolder, self.onError);
                    //self.doRenameFolder(newDocument);
                }
            }
            $("#GB_window_Rename").hide();
        }

        self.onCancel = function () {
            $("#GB_window_Rename").hide();
            $("#GB_window").hide();
            $("#GB_window_Delete").hide();
        }

        self.doRenameFolder = function () {
            self.currentLibraryItems.removeAll();
            var itemEnumerator = self.itemCollection.getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.currentLibraryItems.push(itemEnumerator.get_current());
            }
            for (var num in self.folderCollection()) {
                if (self.folderCollection()[num].selected()) {
                    for (var number in self.currentLibraryItems()) {
                        if (self.currentLibraryItems()[number].get_fieldValues().FileRef == self.folderCollection()[num].folder.get_serverRelativeUrl()) {
                            self.currentLibraryItems()[number].set_item('Title', newDocument);
                            self.currentLibraryItems()[number].set_item('FileLeafRef', newDocument);
                            self.currentLibraryItems()[number].update();
                        }
                    }
                }
            }
            for (var num in self.fileCollection()) {
                if (self.fileCollection()[num].selected()) {
                    for (var number in self.currentLibraryItems()) {
                        if (self.currentLibraryItems()[number].get_fieldValues().FileRef == self.fileCollection()[num].file.get_serverRelativeUrl()) {
                            self.currentLibraryItems()[number].set_item('Title', newDocument);
                            self.currentLibraryItems()[number].set_item('FileLeafRef', newDocument);
                            self.currentLibraryItems()[number].update();
                        }
                    }
                }
            }
            onCopyActive = true;
            self.appWebContext.executeQueryAsync(self.done, self.onError);
        }

        self.doNewFolder = function (parentFolder,name) {
            parentFolder.get_folders().add(name);
            onCopyActive = true;
            parentFolder.update();
            self.appWebContext.executeQueryAsync(self.done, self.onError);
        }

        self.doinvertSelection = function () {
            for (var num in self.fileCollection()) {
                if (self.fileCollection()[num].selected()) {
                    self.fileCollection()[num].selected(false);
                }
                else
                    self.fileCollection()[num].selected(true);
            }
            for (var num in self.folderCollection()) {
                if (self.folderCollection()[num].selected()) {
                    self.folderCollection()[num].selected(false);
                }
                else
                    self.folderCollection()[num].selected(true);
            }
            self.CheckButtonsActivate();
        }

        self.doselectNone = function () {
            for (var num in self.fileCollection()) {
                self.fileCollection()[num].selected(false);
            }
            for (var num in self.folderCollection()) {
                self.folderCollection()[num].selected(false);
            }
            self.CheckButtonsActivate();
        }

        self.doselectAll = function () {
            for (var num in self.fileCollection()) {
                self.fileCollection()[num].selected(true);
            }
            for (var num in self.folderCollection()) {
                self.folderCollection()[num].selected(true);
            }
            self.CheckButtonsActivate();
        }

        self.done = function () {
            mainself.CancelWait();
            LibraryToReset = null;
            if (onCopyActive) {
                self.temporary = self.currentPosition()[self.currentPosition().length - 1];
                self.temporary2 = self.currentPosition()[self.currentPosition().length - 2];
                for (var num in self.currentPosition()) {
                    if (self.currentPosition()[num].type == "Library")
                        LibraryToReset = self.currentPosition()[num];
                }
                //self.onRedirect(self.currentPosition()[self.currentPosition().length - 2]);
                if (self.currentPosition()[self.currentPosition().length - 1].type == "Library") {
                    LibraryToReset = null;
                    self.onRedirect(self.currentPosition()[self.currentPosition().length - 2]);
                }
                else {
                    self.onRedirect(LibraryToReset);
                }
            }
            
            //self.onRedirect(self.currentPosition()[self.currentPosition().length - 1]);

        }

        self.checkselected = function () {
            var choice = false;
            for (var num in self.fileCollection()) {
                if (self.fileCollection()[num].selected()) {
                    choice = true;
                }
            }
            for (var num in self.folderCollection()) {
                if (self.folderCollection()[num].selected()) {
                    choice = true;
                }

            }

        }

        self.showFolderDatabyClick = function (e) {
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.onHidePath();
            mainself.Wait();
            currentSelection = e;
            e.subfolders.removeAll();
            self.onClearIntensity(self.siteCollection()[0]);
            if (!onCopyActive) {
                self.getDirection(e);
                self.checkforTarget();
                self.folderCollection.removeAll();
                self.fileCollection.removeAll();
                self.CollectionLibraries.removeAll();
                self.CollectionSubsites.removeAll();
                self.CheckButtonsActivate();
            }
            //self.onChangeIntensity(self.siteCollection()[0]);
            self.loadSubFoldersandFiles();
            //self.getFoldersandFiles();

        }

        //var testresult = null;
        self.ShowFolderData = function (e) {
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.onHidePath();
            self.onClearIntensity(self.siteCollection()[0]);
            e.imgIntensity(self.intensityImg[2]);
            currentImg = self.intensityImg[2];
            self.getDirection(e);
            self.checkforTarget();
            e.subfolders.removeAll();
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            self.CollectionLibraries.removeAll();
            self.CollectionSubsites.removeAll();
            self.CheckButtonsActivate();
            mainself.Wait();
            currentSelection = e;
            
            for (var num in self.currentPosition()) {
                if (self.currentPosition()[num].type == "Library") {
                    self.currentLibrary = self.currentPosition()[num];
                }
            }
            /*self.itemCollection = self.currentLibrary.libraryItem.getItems(camlQuery);
            self.appWebContext.load(self.itemCollection);
            self.appWebContext.executeQueryAsync(self.getLibraryItem, self.onError);*/
            self.loadSubFoldersandFiles();

        }

        self.loadSubFoldersandFiles = function () {
            self.currentLibraryItems.removeAll();
            var itemEnumerator = currentSelection.parentFolder.get_folders().getEnumerator();
            while (itemEnumerator.moveNext()) {
                oItem = itemEnumerator.get_current().get_listItemAllFields();
                self.currentLibraryItems.push(oItem);
                self.appWebContext.load(self.currentLibraryItems()[self.currentLibraryItems().length - 1]);
            }
            var itemEnumerator = currentSelection.parentFolder.get_files().getEnumerator();
            while (itemEnumerator.moveNext()) {
                oItem = itemEnumerator.get_current().get_listItemAllFields();
                self.currentLibraryItems.push(oItem);
                self.appWebContext.load(self.currentLibraryItems()[self.currentLibraryItems().length - 1]);
            }
            self.appWebContext.executeQueryAsync(self.getFoldersandFiles, self.onError);
        }

        self.loadLibraryItem = function () {
            self.itemCollection = self.currentLibrary.libraryItem.getItems(camlQuery);
            self.appWebContext.load(self.itemCollection);
            self.appWebContext.executeQueryAsync(self.getLibraryItem, self.onError);
        }

        

        self.getLibraryItem = function () {
            self.currentLibraryItems.removeAll();
            var itemEnumerator = self.itemCollection.getEnumerator();
            while (itemEnumerator.moveNext()) {
                self.currentLibraryItems.push(itemEnumerator.get_current());
            }
            self.getFoldersandFiles();
        }

        self.getFoldersandFiles = function () {
            itemCollection = [];
            folderCollection = [];
            Icon = [];
            $("#OrderUp").hide();
            $("#OrderDown").hide();
            var itemEnumerator = currentSelection.parentFolder.get_folders().getEnumerator();
            var reOrderNewFolders = Array();
            while (itemEnumerator.moveNext()) {
                oItem = itemEnumerator.get_current();
                try{
                    if (oItem.get_name() != "Forms") {
                        folderCollection.push(oItem);
                        var newParent = new Array();
                        for (var number in currentSelection.parent()) {
                            newParent.push(currentSelection.parent()[number]);
                        }
                        newParent.push(currentSelection);
                        for (var number in self.currentLibraryItems()) {
                            if (self.currentLibraryItems()[number].get_fieldValues().FileRef == oItem.get_serverRelativeUrl()) {
                                var dateM = self.currentLibraryItems()[number].get_fieldValues().Modified.localeFormat();
                                var sizeF = null;
                                var ItemProperty = self.currentLibraryItems()[number].get_fieldValues();
                                for (var key in ItemProperty) {
                                    try {
                                        if (key.indexOf("Size") != -1) {
                                            eval("sizeF= ItemProperty." + key + ";");
                                        }
                                    }
                                    catch (err) {

                                    }
                                }
                                reOrderNewFolders.push(new folder(oItem, newParent, self.imgSource[2], dateM, sizeF, ItemProperty.FileRef));
                                //currentSelection.subfolders.push(new folder(oItem, newParent, self.imgSource[2],dateM,sizeF));
                            }
                        }
                        //+currentSelection.subfolders.push(new folder(oItem, newParent, self.imgSource[2], dateM, sizeF));
                    }
                }
                catch (err) {
                }
            }

            reOrderNewFolders.sort(function (a, b) {
                var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                if (nameA < nameB)
                    return -1
                if (nameA > nameB)
                    return 1
                return 0
            });
            for (var number in reOrderNewFolders) {
                currentSelection.subfolders.push(reOrderNewFolders[number]);
            }
            reOrderNewFolders = new Array();

            var itemEnumerator = currentSelection.parentFolder.get_files().getEnumerator();
            while (itemEnumerator.moveNext()) {
                oItem = itemEnumerator.get_current();
                itemCollection.push(oItem);
            }
            if (currentSelection.subfolders().length > 0) {
                for (var count in folderCollection) {
                    var newParent = new Array();
                    for (var number in currentSelection.parent()) {
                        newParent.push(currentSelection.parent()[number]);
                    }
                    newParent.push(currentSelection);
                    if (!onCopyActive)
                        reOrderNewFolders.push(new folder(folderCollection[count], newParent, self.imgSource[2], currentSelection.subfolders()[count].Datemodified(), currentSelection.subfolders()[count].size(), currentSelection.subfolders()[count].path()));
                }
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            /*reOrderNewFolders.sort(function (a, b) {
                a = new Date(a.Datemodified());
                b = new Date(b.Datemodified());
                return a > b ? -1 : a < b ? 1 : 0;
            });*/
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var count in itemCollection) {
                var newIcon = self.appWebContext.get_web().mapToIcon(itemCollection[count].get_name(), '', SP.Utilities.IconSize.Size16);
                Icon.push(newIcon);
            }
            self.appWebContext.executeQueryAsync(self.onAddNewFile, self.onError);
        }

        self.onConvertToKborMb = function (size) {
            var newSize = size / 1024;
            if (newSize > 1024) {
                newSize = newSize / 1024;
                newSize=Math.round(newSize);
                return newSize.toString() + " " + "MB";
            }
            else {
                newSize = Math.round(newSize);
                return newSize.toString() + " " + "KB";
            }

        }

        self.onChangeOrderByA = function () {
            if (orderByApprovalStatusP) {
                orderByApprovalStatusP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left':920,
                });
            }
            else {
                orderByApprovalStatusP = true;
                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 920,
                });

            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderByApprovalStatusP) {
                reOrderNewFiles.sort(function (a, b) {
                    var nameA = String(a.StatusApproval()).toLowerCase(), nameB = String(b.StatusApproval()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }
        }

        self.onChangeOrderByN = function () {
            if (orderByNameP) {
                orderByNameP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left': 175,
                });
            }
            else {
                orderByNameP = true;
                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 175,
                });

            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderByNameP) {
                reOrderNewFiles.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }
        }

        self.onChangeOrderByV = function () {
            if (orderByVersionP) {
                orderByVersionP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left': 835,
                });
            }
            else {
                orderByVersionP = true;
                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 835,
                });

            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderByVersionP) {
                reOrderNewFiles.sort(function (a, b) {
                    var nameA = String(a.Version()).toLowerCase(), nameB = String(b.Version()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    var nameA = String(a.Version()).toLowerCase(), nameB = String(b.Version()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }
        }

        self.onChangeOrderByD = function () {
            if (orderByDateP) {
                orderByDateP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left': 475,
                });
            }
            else {
                orderByDateP = true;
                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 475,
                });
            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderByDateP) {
                reOrderNewFiles.sort(function (a, b) {
                    a = new Date(a.Datemodified());
                    b = new Date(b.Datemodified());
                    return a > b ? -1 : a < b ? 1 : 0;
                });
                reOrderNewFolders.sort(function (a, b) {
                    a = new Date(a.Datemodified());
                    b = new Date(b.Datemodified());
                    return a > b ? -1 : a < b ? 1 : 0;
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    a = new Date(a.Datemodified());
                    b = new Date(b.Datemodified());
                    return a > b ? 1 : a < b ? -1 : 0;
                });
                reOrderNewFolders.sort(function (a, b) {
                    a = new Date(a.Datemodified());
                    b = new Date(b.Datemodified());
                    return a > b ? 1 : a < b ? -1 : 0;
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }

        }

        self.onChangeOrderByP = function () {
            if (orderByPathP) {
                orderByPathP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left': 695,
                });
            }
            else {
                orderByPathP = true;

                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 695,
                });
            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderByPathP) {
                reOrderNewFiles.sort(function (a, b) {
                    var TypeA = String(a.path()).toLowerCase(), TypeB = String(b.path()).toLowerCase()
                    if (TypeA < TypeB)
                        return -1
                    if (TypeA > TypeB)
                        return 1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.path()).toLowerCase(), nameB = String(b.path()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    var TypeA = String(a.path()).toLowerCase(), TypeB = String(b.path()).toLowerCase()
                    if (TypeA < TypeB)
                        return 1
                    if (TypeA > TypeB)
                        return -1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.path()).toLowerCase(), nameB = String(b.path()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }

        }

        self.onChangeOrderByT = function () {
            if (orderByTypeP) {
                orderByTypeP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left': 650,
                });
            }
            else {
                orderByTypeP = true;

                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 650,
                });
            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderByTypeP) {
                reOrderNewFiles.sort(function (a, b) {
                    var TypeA = String(a.specificType()).toLowerCase(), TypeB = String(b.specificType()).toLowerCase()
                    if (TypeA < TypeB)
                        return -1
                    if (TypeA > TypeB)
                        return 1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    var TypeA = String(a.specificType()).toLowerCase(), TypeB = String(b.specificType()).toLowerCase()
                    if (TypeA < TypeB)
                        return 1
                    if (TypeA > TypeB)
                        return -1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }

        }


        self.onChangeOrderByS = function () {
            if (orderBySizeP) {
                orderBySizeP = false;
                $("#OrderUp").hide();
                $("#OrderDown").show();
                $("#OrderDown").css({
                    'top': 2,
                    'left': 750,
                });
            }
            else {
                orderBySizeP = true;

                $("#OrderUp").show();
                $("#OrderDown").hide();
                $("#OrderUp").css({
                    'top': 2,
                    'left': 750,
                });
            }
            var reOrderNewFolders = new Array();
            var reOrderNewFiles = new Array();
            for (var number in self.folderCollection()) {
                reOrderNewFolders.push(self.folderCollection()[number]);
            }
            for (var number in self.fileCollection()) {
                reOrderNewFiles.push(self.fileCollection()[number]);
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            if (orderBySizeP) {
                reOrderNewFiles.sort(function (a, b) {
                    if (a.size() < b.size())
                        return -1
                    if (a.size() > b.size())
                        return 1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return -1
                    if (nameA > nameB)
                        return 1
                    return 0
                });
            }
            else {
                reOrderNewFiles.sort(function (a, b) {
                    if (a.size() < b.size())
                        return 1
                    if (a.size() > b.size())
                        return -1
                    return 0
                });
                reOrderNewFolders.sort(function (a, b) {
                    var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                    if (nameA < nameB)
                        return 1
                    if (nameA > nameB)
                        return -1
                    return 0
                });
            }
            for (var number in reOrderNewFolders) {
                self.folderCollection.push(reOrderNewFolders[number]);
            }
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }

        }

        self.onAddNewFile = function () {
            var reOrderNewFiles = new Array();
            for (var count in itemCollection) {
                if (!onCopyActive) {
                    for (var number in self.currentLibraryItems()) {
                        if (self.currentLibraryItems()[number].get_fieldValues().FileRef == itemCollection[count].get_serverRelativeUrl()) {
                            var dateM = self.currentLibraryItems()[number].get_fieldValues().Modified.localeFormat();
                            var sizeF = null;
                            var typeF = null;
                            var ModerationS=null;
                            var ItemProperty = self.currentLibraryItems()[number].get_fieldValues();
                            for (var key in ItemProperty) {
                                try {
                                    if (key.indexOf("_Size") != -1) {
                                        eval("sizeF= ItemProperty." + key + ";");
                                        sizeF = self.onConvertToKborMb(sizeF);
                                    }
                                    if (key.indexOf("_ModerationStatus") != -1) {
                                        eval("ModerationS= ItemProperty." + key + ";");
                                    }
                                    if (key.indexOf("_Type") != -1 && key.indexOf("HTML") == -1) {
                                        eval("typeF= ItemProperty." + key + ";");
                                    }
                                }
                                catch (err) {

                                }
                            }
                            reOrderNewFiles.push(new file(itemCollection[count], Icon[count], dateM, typeF, sizeF, ItemProperty.FileRef));
                            reOrderNewFiles[reOrderNewFiles.length - 1].moderationStatus(ModerationS);
                            //self.fileCollection.push(new file(itemCollection[count], Icon[count],dateM,typeF,sizeF));
                        }
                    }
                    
                }

            }
            reOrderNewFiles.sort(function (a, b) {
                var nameA = String(a.formattedName()).toLowerCase(), nameB = String(b.formattedName()).toLowerCase()
                if (nameA < nameB)
                    return -1
                if (nameA > nameB)
                    return 1
                return 0
            });
            for (var number in reOrderNewFiles) {
                self.fileCollection.push(reOrderNewFiles[number]);
            }
            for (var count in currentSelection.subfolders()) {
                currentSelection.subfolders()[count];
            }
            Itemcount = currentSelection.subfolders().length;
            for (var count in currentSelection.subfolders()) {
                self.appWebContext.load(currentSelection.subfolders()[count].parentFolder, 'Folders');
                self.appWebContext.load(currentSelection.subfolders()[count].parentFolder, 'Files');
                self.appWebContext.executeQueryAsync(self.loadsubFolders, self.onError);
            }
            if (Itemcount == 0)
                mainself.CancelWait();
        }



        self.loadsubFolders = function () {
            Itemcount--;
            if (Itemcount == 0) {

                mainself.CancelWait();
                if (LibraryToReset != null && onCopyActive) {
                    LibraryToReset = null;
                    self.onRedirect(self.temporary2);
                }
                else if (onCopyActive) {
                    onCopyActive = false;
                    var correctCurrentS = null;
                    for (var number in currentSelection.subfolders()) {
                        if (currentSelection.subfolders()[number].folder.get_name() == self.temporary.folder.get_name())
                            correctCurrentS = currentSelection.subfolders()[number];  
                    }
                    self.onRedirect(correctCurrentS);
                }
                else {
                    for (var count in currentSelection.subfolders()) {
                        itemEnumerator = currentSelection.subfolders()[count].parentFolder.get_folders().getEnumerator();
                        //itemEnumerator.moveNext();
                        if (itemEnumerator.moveNext()) {
                            currentSelection.subfolders()[count].imgSource(self.imgSource[0]);
                        }
                    }
                    if (currentSelection.imgSource() == self.imgSource[0]) {
                        if (currentSelection.imgSource() != self.imgSource[2]) {
                            currentSelection.imgSource(self.imgSource[1]);
                        }

                    }
                    else {
                        if (currentSelection.imgSource() != self.imgSource[2]) {
                            currentSelection.imgSource(self.imgSource[0]);
                            currentSelection.subfolders.removeAll();
                        }
                    }
                }
            }


        }

        self.OnKeyDown = function (e) {
            var w = e;
        }


        self.onError = function (sender, args) {
            alert('Request failed. ' + args.get_message() +
            '\n' + args.get_stackTrace());
            mainself.CancelWait();
        }
   
        self.NavigatorDirect = function (e) {
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.onHidePath();
            mainself.Wait();
            currentSelection = e;
            if (!onCopyActive) {
                self.getDirection(e);
                self.checkforTarget();
                self.folderCollection.removeAll();
                self.fileCollection.removeAll();
                self.CollectionLibraries.removeAll();
                self.CollectionSubsites.removeAll();
                self.CheckButtonsActivate();
            }
            $("#" + String(currentSelection.site.get_id())).show();
            currentSelection.imgSource(self.imgSource[1]);
            self.onClearIntensity(self.siteCollection()[0]);
            currentSelection.imgIntensity(self.intensityImg[2]);
            currentImg = self.intensityImg[2];
            currentSelection.itemCollection = currentSelection.site.get_lists();
            self.subSiteCollection = currentSelection.site.get_webs();
            self.appWebContext.load(currentSelection.itemCollection);
            self.appWebContext.load(self.subSiteCollection);
            self.appWebContext.executeQueryAsync(self.onGetSiteInfo, self.onError);


        }
        self.Navigator = function (e) {
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divSearchRibbon").hide();
            $("#divWorkflowRibbon").hide();
            self.onHidePath();
            self.getDirection(e);
            self.checkforTarget();
            if (e.libraries().length == 0 && e.subSites().length == 0) {
                mainself.Wait();
                currentSelection = e;
                self.folderCollection.removeAll();
                self.fileCollection.removeAll();
                self.CollectionLibraries.removeAll();
                self.CollectionSubsites.removeAll();
                self.CheckButtonsActivate();
                $("#" + String(currentSelection.site.get_id())).show();
                currentSelection.imgSource(self.imgSource[1]);
                self.onClearIntensity(self.siteCollection()[0]);
                currentSelection.imgIntensity(self.intensityImg[2]);
                currentImg = self.intensityImg[2];
                currentSelection.itemCollection = currentSelection.site.get_lists();
                currentSelection.recycleBin = currentSelection.site.get_recycleBin();
                self.subSiteCollection = currentSelection.site.get_webs();
                self.appWebContext.load(currentSelection.itemCollection);
                self.appWebContext.load(currentSelection.recycleBin);
                self.appWebContext.load(self.subSiteCollection);
                self.appWebContext.executeQueryAsync(self.onGetSiteInfo, self.onError);

                
            }
            else if (e.imgSource() == self.imgSource[1]) {
                self.folderCollection.removeAll();
                self.fileCollection.removeAll();
                self.CollectionLibraries.removeAll();
                self.CollectionSubsites.removeAll();
                self.CheckButtonsActivate();
                self.onClearIntensity(self.siteCollection()[0]);
                e.imgIntensity(self.intensityImg[2]);
                currentImg = self.intensityImg[2];
                $("#" + String(e.site.get_id())).hide();
                e.imgSource(self.imgSource[0]);
            }
            else if (e.imgSource() == self.imgSource[0]) {
                self.folderCollection.removeAll();
                self.fileCollection.removeAll();
                self.CollectionLibraries.removeAll();
                self.CollectionSubsites.removeAll();
                self.CheckButtonsActivate();
                self.onClearIntensity(self.siteCollection()[0]);
                e.imgIntensity(self.intensityImg[2]);
                currentImg = self.intensityImg[2];
                $("#" + String(e.site.get_id())).show();
                for (var count in e.libraries()) {
                    if(!onCopyActive)
                        self.CollectionLibraries.push(e.libraries()[count]);
                }
                for (var count in e.subSites()) {
                    if(!onCopyActive)
                        self.CollectionSubsites.push(e.subSites()[count]);
                }
                e.imgSource(self.imgSource[1]);
            }


        }





        self.onGetSiteInfo = function () {
            valueLoading = true;
            var itemEnumerator = currentSelection.itemCollection.getEnumerator();
            currentSelection.softedItemCollection = [];
            while (itemEnumerator.moveNext()) {
                currentSelection.softedItemCollection.push(itemEnumerator.get_current());
            }

            currentSelection.softedItemCollection.sort(function (a, b) {
                var nameA = String(a.get_title()).toLowerCase(), nameB = String(b.get_title()).toLowerCase();
                if (nameA < nameB)
                    return -1;
                if (nameA > nameB)
                    return 1;
                return 0;
            });

            if (currentSelection.libraries().length > 0) {
                //for (var num in currentSelection.libraries())
                currentSelection.libraries.removeAll();
            }
            if (currentSelection.subSites().length > 0) {
                //for (var num in currentSelection.subSites())
                currentSelection.subSites.removeAll();
            }
            for (var count in currentSelection.softedItemCollection) {
                try {
                    if (currentSelection.softedItemCollection[count].get_baseType() == 0) {
                        //currentSelection.lists.push(new List(currentSelection.softedItemCollection[count]));
                    }
                    else {
                        if (!currentSelection.softedItemCollection[count].get_hidden()) {
                            //var Icon = currentSelection.site.mapToIcon(currentSelection.softedItemCollection[count].get_fieldValues().FileLeafRef, SP.Utilities.IconSize.Size16);
                            var newParent = new Array();
                            for (var number in currentSelection.parent()) {
                                newParent.push(currentSelection.parent()[number]);
                            }
                            newParent.push(currentSelection);
                            currentSelection.libraries.push(new Library(currentSelection.softedItemCollection[count], self.imgSource[2], newParent,false));
                            if (!onCopyActive)
                                self.CollectionLibraries.push(new Library(currentSelection.softedItemCollection[count], self.imgSource[2], newParent,false));
                        }
                        else if(!currentSelection.softedItemCollection[count].get_isPrivate()){
                            var newParent = new Array();
                            for (var number in currentSelection.parent()) {
                                newParent.push(currentSelection.parent()[number]);
                            }
                            newParent.push(currentSelection);
                            currentSelection.libraries.push(new Library(currentSelection.softedItemCollection[count], self.imgSource[2], newParent,true));
                            if (!onCopyActive)
                                self.CollectionLibraries.push(new Library(currentSelection.softedItemCollection[count], self.imgSource[2], newParent,true));
                        }
                    }
                }
                catch (err) {
                    //currentSelection.subSites.push(new Site(currentSelection.softedItemCollection[count], self.imgSource[0]));
                }

            }
            currentSelection.softedItemCollection = [];
            itemEnumerator = self.subSiteCollection.getEnumerator();
            while (itemEnumerator.moveNext()) {
                if(itemEnumerator.get_current().get_webTemplate()!="APP")
                    currentSelection.softedItemCollection.push(itemEnumerator.get_current());
            }
            currentSelection.softedItemCollection.sort(function (a, b) {
                var nameA = String(a.get_title()).toLowerCase(), nameB = String(b.get_title()).toLowerCase();
                if (nameA < nameB)
                    return -1;
                if (nameA > nameB)
                    return 1;
                return 0;
            });
            Icon = [];
            for (var count in currentSelection.softedItemCollection) {
                var newIcon = self.appWebContext.get_web().mapToIcon(currentSelection.softedItemCollection[count].get_title(), '', SP.Utilities.IconSize.Size16);
                Icon.push(newIcon);
            }
            self.appWebContext.executeQueryAsync(self.onAddNewSubsite, self.onError);
        }

        self.onAddNewSubsite = function () {
            for (var count in currentSelection.softedItemCollection) {
                var newParent = new Array();
                for (var number in currentSelection.parent()) {
                    newParent.push(currentSelection.parent()[number]);
                }
                newParent.push(currentSelection);
                currentSelection.subSites.push(new Site(currentSelection.softedItemCollection[count], self.imgSource[0], Icon[count], newParent));
                if (!onCopyActive)
                    self.CollectionSubsites.push(new Site(currentSelection.softedItemCollection[count], self.imgSource[0], Icon[count], newParent));
            }
            Itemcount = currentSelection.libraries().length + currentSelection.subSites().length;
            for (var number in currentSelection.subSites()) {
                self.appWebContext.load(currentSelection.subSites()[number].parentFolder);
                self.appWebContext.executeQueryAsync(self.loadLibraryFolders, self.onError);
            }
            
            for (var count in currentSelection.libraries()) {
                self.appWebContext.load(currentSelection.libraries()[count].parentFolder);
                self.appWebContext.load(currentSelection.libraries()[count].parentFolder, 'Folders');
                self.appWebContext.load(currentSelection.libraries()[count].parentFolder, 'Files');
                self.appWebContext.executeQueryAsync(self.loadLibraryFolders, self.onError);
            }

        }

        self.onSearch = function () {
            if (self.currentPosition().length > 0) {
                mainself.Wait();
                $("#divSearchRibbon").show();
                $("#divRibbon").hide();
                $("#divRecycleRibbon").hide();
                $("#divWorkflowRibbon").hide();
                onSearch = true;
                if (currentSearch == null || self.currentPosition()[0].type!="Search") {
                    currentSearch = new searchDirection(self.currentPosition()[self.currentPosition().length - 1]);
                }
                if (currentSearch.searchDirectory.type != "Site") {
                    self.onSearchSite(false);
                }
                else
                    self.onSearchSite(true);
                //var SearchDesUrl = self.siteCollection()[0].site.get_url()+ self.currentPosition()[self.currentPosition().length - 1].parentFolder.get_serverRelativeUrl();
                var SearchDesUrl = self.siteCollection()[0].site.get_url();
                SearchDesUrl = SearchDesUrl.substring(0, SearchDesUrl.length - self.siteCollection()[0].parentFolder.get_serverRelativeUrl().length+1);
                SearchDesUrl += self.currentPosition()[self.currentPosition().length - 1].parentFolder.get_serverRelativeUrl();
                var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(self.appWebContext);
                var queryText = 'Title:"' + self.SearchKeyValue() + '*" AND Path:"' + SearchDesUrl + '*"';
                //var queryText = 'Path:"' + SearchDesUrl + '*"';
                keywordQuery.set_queryText(queryText);
                var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(self.appWebContext);

                results = searchExecutor.executeQuery(keywordQuery);
                self.appWebContext.executeQueryAsync(self.onGetSearchSuccess, self.onError);
            }

        }

        self.onCHeckSubSite = function (value) {
            if (currentSearch.searchDirectory.type == "Site") {
                var directoryValue = value.Path;
                var directions = new Array();
                directoryValue = directoryValue.substring(value.SiteName.length);
                directions = directoryValue.split('/');
                directoryValue = directions[1];
                for (var num in currentSearch.searchDirectory.subSites()) {
                    if (currentSearch.searchDirectory.subSites()[num].site.get_title() == directoryValue) {
                        return false
                    }
                }
                return true;
            }
            else
                return true;
        }

        self.onGetSearchSuccess = function () {
            try{
                searchfolders = [];
                searchfiles = [];
                var currentSite = null;
                if (results.get_value().ResultTables[0].ResultRows.length > 0) {

                    for (var number in results.get_value().ResultTables[0].ResultRows) {
                        /*if (results.get_value().ResultTables[0].ResultRows[number].IsContainer && results.get_value().ResultTables[0].ResultRows[number].contentclass.indexOf("Library")!=-1) {
                            searchfolders.push(results.get_value().ResultTables[0].ResultRows[number]);
                        }*/
                        if (!results.get_value().ResultTables[0].ResultRows[number].IsContainer && results.get_value().ResultTables[0].ResultRows[number].contentclass.indexOf("Library") != -1 && results.get_value().ResultTables[0].ResultRows[number].contentclass.indexOf("ListItem") != -1) {
                            if (self.onSearchSite()) {
                                if (SearchSubsite) {
                                    searchfiles.push(results.get_value().ResultTables[0].ResultRows[number]);
                                }
                                else {
                                    if (self.onCHeckSubSite(results.get_value().ResultTables[0].ResultRows[number])) {
                                        searchfiles.push(results.get_value().ResultTables[0].ResultRows[number]);
                                    }

                                }
                            }
                            else {
                                if (SearchSubsite) {
                                    searchfiles.push(results.get_value().ResultTables[0].ResultRows[number]);
                                }
                                else {
                                    var currentParentDirection = results.get_value().ResultTables[0].ResultRows[number].ParentLink;
                                    currentParentDirection = currentParentDirection.substring(results.get_value().ResultTables[0].ResultRows[number].SiteName.length + 1);
                                    currentParentDirection = self.siteCollection()[0].parentFolder.get_serverRelativeUrl() + currentParentDirection;
                                    if (currentParentDirection == currentSearch.parentFolder.get_serverRelativeUrl()) {
                                        searchfiles.push(results.get_value().ResultTables[0].ResultRows[number]);
                                    }

                                }
                            }
                        }

                    }
                    currentSelection = self.siteCollection()[0];
                    /*self.appWebContext.load(currentSelection.parentFolder, "Folders");
                    self.appWebContext.load(currentSelection.parentFolder, "Files");
                    self.appWebContext.executeQueryAsync(self.onGetSiteSearch, self.onError);*/
                    self.onGetSiteSearch();
                }
                else
                    mainself.CancelWait();
            }
            catch(err){
                mainself.CancelWait();
            }

        }

        self.onGetSiteSearch = function () {
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            self.CollectionLibraries.removeAll();
            self.CollectionSubsites.removeAll();
            currentSearch.folders.removeAll();
            currentSearch.files.removeAll();
            countResults = searchfolders.length + searchfiles.length;
            searchfilesitem = [];
            searchfoldersitem = [];
            serverUrl = currentSelection.site.get_serverRelativeUrl();
            for (var folNum in searchfolders) {
                var customUrl = searchfolders[folNum].Path;
                customUrl = customUrl.substring(searchfolders[folNum].SiteName.length);
                customUrl = serverUrl + customUrl;
                searchfoldersitem.push(currentSelection.site.getFolderByServerRelativeUrl(customUrl));
                self.appWebContext.load(searchfoldersitem[searchfoldersitem.length - 1]);
                self.appWebContext.executeQueryAsync(self.onMakeNewSearchItem, self.onMakeNewSearchItem);
                //self.onMakeNewSearchItemFolder(searchfolders[folNum]);
            }
            for (var filNum in searchfiles) {
                
                var customUrl = searchfiles[filNum].Path;
                customUrl = customUrl.substring(searchfiles[filNum].SiteName.length);
                customUrl = serverUrl + customUrl;
                searchfilesitem.push(currentSelection.site.getFileByServerRelativeUrl(customUrl));
                self.appWebContext.load(searchfilesitem[searchfilesitem.length - 1]);
                self.appWebContext.executeQueryAsync(self.onMakeNewSearchItem, self.onMakeNewSearchItem);
                //self.onMakeNewSearchItemFile(searchfiles[filNum]);

            }
            
        }

        self.onMakeNewSearchItem = function () {
            countResults--;
            if (countResults == 0) {

                for (num in searchfoldersitem) {
                    self.folderCollection.push(new folder(searchfoldersitem[num], new Array()[searchfoldersitem[num]], self.imgSource[2], searchfolders[num].LastModifiedTime.toLocaleString(), searchfolders[num].Size, searchfolders[num].Path));
                }
                for (var num in self.folderCollection()) {
                    currentSearch.folders.push(self.folderCollection()[num]);
                }
                for (var number in currentSearch.folders()) {
                    self.appWebContext.load(currentSearch.folders()[number].parentFolder, "Folders");
                    self.appWebContext.executeQueryAsync();
                }
                Icon = [];
                for (var count in searchfilesitem) {
                    try{
                        var newIcon = self.appWebContext.get_web().mapToIcon(searchfilesitem[count].get_name(), '', SP.Utilities.IconSize.Size16);
                        Icon.push(newIcon);
                    }
                    catch(err){
                    }
                }
                self.appWebContext.executeQueryAsync(self.onAddNewFilesIcon, self.onError);
            }
        }

        self.onAddNewFilesIcon = function () {
            for (num in searchfilesitem) {
                try{
                    var sizeF = self.onConvertToKborMb(searchfilesitem[num].Size);
                    self.fileCollection.push(new file(searchfilesitem[num], Icon[num], searchfiles[num].LastModifiedTime.toLocaleString(), searchfiles[num].FileType, sizeF, searchfiles[num].Path));
                }
                catch (err) {
                }
            }

            for (var num in self.fileCollection()) {
                currentSearch.files.push(self.fileCollection()[num]);
            }
            self.currentPositionBeforeSearch.removeAll();
            for (var num in self.currentPosition()) {
                self.currentPositionBeforeSearch.push(self.currentPosition()[num]);
            }
            self.getDirection(currentSearch);
            self.onShowPath();
            mainself.CancelWait();
        }

        self.loadLibraryFolders = function () {
            Itemcount--;
            if (Itemcount == 0) {
                for (var count in currentSelection.libraries()) {
                    itemEnumerator = currentSelection.libraries()[count].parentFolder.get_folders().getEnumerator();
                    itemEnumerator.moveNext();
                    if (itemEnumerator.moveNext()) {
                        //if (itemEnumerator.get_current().get_name().indexOf("_") != 0 && itemEnumerator.get_current().get_name().indexOf("Form")==-1)
                        currentSelection.libraries()[count].imgSource(self.imgSource[0]);
                    }
                }
                mainself.CancelWait();
                if (self.redirectListID != null) {
                    var editedListID = self.redirectListID.substring(1,self.redirectListID.length-1);
                    var accurateList = null;
                    for (var count in currentSelection.libraries()) {
                        if (currentSelection.libraries()[count].libraryItem.get_id().toString() == editedListID) {
                            accurateList = currentSelection.libraries()[count];
                            self.redirectListID = null;
                        }
                    }
                    self.ShowLibraryData(accurateList);
                }
                if (onCopyActive) {
                    onCopyActive = false;
                    if (self.temporary.type = "Library") {
                        var correctnum = 0;
                        for (var num in currentSelection.libraries()) {
                            if (currentSelection.libraries()[num].formattedName() == self.temporary.formattedName()) {
                                correctnum = num;
                            }
                        }
                        self.onRedirect(currentSelection.libraries()[correctnum]);
                    }
                    else
                        self.onRedirect(self.temporary);
                }
            }



        }

        self.onShowPath = function () {
            $(".orderPath").show();
            $(".orderType").hide();
            $(".orderSize").hide();
        }
        self.onHidePath = function () {
            $(".orderPath").hide();
            $(".orderType").show();
            $(".orderSize").show();

        }

        self.LoadReCycleBin = function (e) {
            currentSelection = e;
            mainself.CancelWait();
            mainself.Wait();
            self.onClearIntensity(self.siteCollection()[0]);
            self.enableImgRecy(e);
            self.currentPosition.removeAll();
            self.currentPosition.push(e.recycleBinPresent());
            self.appWebContext.load(currentSelection.recycleBin);
            self.appWebContext.executeQueryAsync(self.ShowReCycleBin, self.onError);

        }

        self.ShowReCycleBin = function (e) {
            ReCycleItems = [];

            Icon = [];
            var itemEnumerator = currentSelection.recycleBin.getEnumerator();
            while (itemEnumerator.moveNext()) {
                ReCycleItems.push(itemEnumerator.get_current());
            }
            self.folderCollection.removeAll();
            self.fileCollection.removeAll();
            self.CollectionLibraries.removeAll();
            self.CollectionSubsites.removeAll();
            for (var num in ReCycleItems) {
                if (ReCycleItems[num].get_itemType() == 1) {
                    var newIcon = self.appWebContext.get_web().mapToIcon(ReCycleItems[num].get_leafName(), '', SP.Utilities.IconSize.Size16);
                    Icon.push(newIcon);
                    //self.fileCollection.push(new file(array[num], null, null, "File", self.onConvertToKborMb(array[num].get_size()), null));
                }
            }
            self.appWebContext.executeQueryAsync(self.onAddNewRecycle, self.onError);

        }

        self.onAddNewRecycle = function () {
            var fileContainer = new Array();
            for (var num in ReCycleItems) {
                if (ReCycleItems[num].get_itemType() == 1) {
                    fileContainer.push(ReCycleItems[num]);
                }
                else {
                    self.folderCollection.push(new folder(ReCycleItems[num], new Array(), self.imgSource[2], ReCycleItems[num].get_deletedDate().localeFormat(), 0, ReCycleItems[num].get_dirName()));
                }
            }
            for (var num in fileContainer) {
                self.fileCollection.push(new file(fileContainer[num], Icon[num], fileContainer[num].get_deletedDate().localeFormat(), "File", self.onConvertToKborMb(ReCycleItems[num].get_size()),null));
            }
            var s = 0;
            mainself.CancelWait();
            $("#divSearchRibbon").hide();
            $("#divRibbon").hide();
            $("#divRecycleRibbon").show();
            $("#divWorkflowRibbon").hide();
            self.onShowPath();
        }

        self.onEmptyReh = function () {
            mainself.Wait();
            currentSelection.site.get_recycleBin().deleteAll();
            /*for (var num in self.fileCollection()) {
                self.fileCollection()[num].file.deleteObject();
            }
            for (var num in self.folderCollection()) {
                self.folderCollection()[num].folder.deleteObject();
            }*/
            self.appWebContext.executeQueryAsync(self.LoadReCycleBin(currentSelection), self.onError);
        }

        self.onresAll = function () {
            mainself.Wait();
            /*
            for (var num in self.fileCollection()) {
                self.fileCollection()[num].file.restore();
            }
            for (var num in self.folderCollection()) {
                self.folderCollection()[num].folder.restore();
            }*/
            currentSelection.site.get_recycleBin().restoreAll();
            self.appWebContext.executeQueryAsync(self.LoadReCycleBin(currentSelection), self.onError);
        }

        self.onResSe = function () {
            mainself.Wait();
            for (var num in self.fileCollection()) {
                if(self.fileCollection()[num].selected())
                    self.fileCollection()[num].file.restore();
            }
            for (var num in self.folderCollection()) {
                if(self.folderCollection()[num].selected())
                    self.folderCollection()[num].folder.restore();
            }
            self.appWebContext.executeQueryAsync(self.LoadReCycleBin(currentSelection), self.onError);
        }


        self.CheckforHiddenLibraries = function () {
            if (!self.ShowHiddenLibraries()) {
                $(".isHiddenLirary").show();
            }
            else {
                $(".isHiddenLirary").hide();
            }

        }

        self.onOpenFile = function (e) {
            window.open(e.path());
        }

        var numFolder = 0;

        self.publishFiles = function () {
            //mainself.Wait();
            if (self.CurrentImgpublishFiles() == self.ImgpublishFiles[2]) {
                filesToPuborAp = [];
                numFolder = 0;
                isPublish = true;
                for (var num in self.fileCollection()) {
                    if (self.fileCollection()[num].selected()) {
                        filesToPuborAp.push(self.fileCollection()[num].file);
                        //self.fileCollection()[num].file.publish();
                    }
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        numFolder++;
                    }
                }
                //numFolder = self.folderCollection().length;
                if (numFolder == 0) {
                    for (var num in filesToPuborAp) {
                        if (filesToPuborAp[num].get_level() == 2)
                            filesToPuborAp[num].publish();
                        //self.appWebContext.executeQueryAsync();
                    }
                    onCopyActive = true;
                    isPublish = false;
                    self.appWebContext.executeQueryAsync(self.done, self.onError);
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        self.addFiles(self.folderCollection()[num]);
                    }
                }

            }

        }

        self.addFiles = function (folder) {
            var currentFolderPath = folder.folder.get_serverRelativeUrl();
            for (var num in self.currentLibraryItems()) {
                if ( self.currentLibraryItems()[num].get_fieldValues().FileRef.indexOf(currentFolderPath) != -1 && self.currentLibraryItems()[num].get_fileSystemObjectType() == 0) {
                    filesToPuborAp.push(self.currentLibraryItems()[num].get_file());
                    self.appWebContext.load(filesToPuborAp[filesToPuborAp.length - 1]);
                }
            }
            self.appWebContext.executeQueryAsync(self.finishAddFile, self.onError);
        }
        self.finishAddFile = function () {
            numFolder--
            if (numFolder == 0) {
                for (var num in filesToPuborAp) {
                    if (filesToPuborAp[num].get_level() == 2&& isPublish)
                        filesToPuborAp[num].publish();
                    if (filesToPuborAp[num].get_level() == 1&& isunPublish)
                        filesToPuborAp[num].unPublish();
                    //self.appWebContext.executeQueryAsync();
                }
                onCopyActive = true;
                isPublish = false;
                isunPublish = false;
                self.appWebContext.executeQueryAsync(self.done, self.onError);
            }
        }

        self.addFilesApprove = function (folder) {
            var currentFolderPath = folder.folder.get_serverRelativeUrl();
            for (var num in self.currentLibraryItems()) {
                if (self.currentLibraryItems()[num].get_fieldValues().FileRef.indexOf(currentFolderPath) != -1 && self.currentLibraryItems()[num].get_fileSystemObjectType() == 0) {
                    filesToPuborAp.push(self.currentLibraryItems()[num].get_file());
                    self.appWebContext.load(filesToPuborAp[filesToPuborAp.length - 1]);
                }
            }
            self.appWebContext.executeQueryAsync(self.finishAddFileApprove, self.onError);
        }
        self.finishAddFileApprove = function () {
            numFolder--
            if (numFolder == 0) {
                for (var num in filesToPuborAp) {
                    if (filesToPuborAp[num].get_level() == 2&& isApprove)
                        filesToPuborAp[num].approve('');
                    if(filesToPuborAp[num].get_level() == 2&& isReject)
                        filesToPuborAp[num].deny('');
                    //self.appWebContext.executeQueryAsync();
                }
                onCopyActive = true;
                isApprove = false;
                isReject = false;
                self.appWebContext.executeQueryAsync(self.done, self.onError);
            }
        }

        self.onChangeToWorkflow = function () {
            $("#divSearchRibbon").hide();
            $("#divRibbon").hide();
            $("#divRecycleRibbon").hide();
            $("#divWorkflowRibbon").show();
        }

        self.onChangeToHome = function () {
            $("#divSearchRibbon").hide();
            $("#divRibbon").show();
            $("#divRecycleRibbon").hide();
            $("#divWorkflowRibbon").hide();

        }

        self.approveFiles = function () {
            if (self.CurrentImgapproveFiles() == self.ImgapproveFiles[2]) {
                filesToPuborAp = [];
                numFolder = 0;
                isAppove = true;
                for (var num in self.fileCollection()) {
                    if (self.fileCollection()[num].selected()) {
                        filesToPuborAp.push(self.fileCollection()[num].file);
                    }
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        numFolder++;
                    }
                }
                //numFolder = self.folderCollection().length;
                if (numFolder == 0) {
                    for (var num in filesToPuborAp) {
                        filesToPuborAp[num].approve('');
                        //self.appWebContext.executeQueryAsync();
                    }
                    onCopyActive = true;
                    isApprove = false;
                    self.appWebContext.executeQueryAsync(self.done, self.onError);
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        self.addFilesApprove(self.folderCollection()[num]);
                    }
                }
            }

        }

        self.rejectFiles = function () {
            if (self.CurrentImgrejectFiles() == self.ImgrejectFiles[2]) {
                filesToPuborAp = [];
                numFolder = 0;
                isReject = true;
                for (var num in self.fileCollection()) {
                    if (self.fileCollection()[num].selected()) {
                        filesToPuborAp.push(self.fileCollection()[num].file);
                    }
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        numFolder++;
                    }
                }
                //numFolder = self.folderCollection().length;
                if (numFolder == 0) {
                    for (var num in filesToPuborAp) {
                        filesToPuborAp[num].deny('');
                        //self.appWebContext.executeQueryAsync();
                    }
                    onCopyActive = true;
                    isReject = false;
                    self.appWebContext.executeQueryAsync(self.done, self.onError);
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        self.addFilesApprove(self.folderCollection()[num]);
                    }
                }
            }

        }

        self.unpublishFiles = function () {
            if (self.CurrentImgunpublishFiles() == self.ImgunpublishFiles[2] || self.CurrentImgcancelapproveFiles() == self.ImgcancelapproveFiles[2]) {
                filesToPuborAp = [];
                numFolder = 0;
                isunPublish = true;
                for (var num in self.fileCollection()) {
                    if (self.fileCollection()[num].selected()) {
                        filesToPuborAp.push(self.fileCollection()[num].file);
                        //self.fileCollection()[num].file.publish();
                    }
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        numFolder++;
                    }
                }
                //numFolder = self.folderCollection().length;
                if (numFolder == 0) {
                    for (var num in filesToPuborAp) {
                        if (filesToPuborAp[num].get_level() == 1)
                            filesToPuborAp[num].unPublish();
                        //self.appWebContext.executeQueryAsync();
                    }
                    onCopyActive = true;
                    isunPublish = false;
                    self.appWebContext.executeQueryAsync(self.done, self.onError);
                }
                for (var num in self.folderCollection()) {
                    if (self.folderCollection()[num].selected()) {
                        self.addFiles(self.folderCollection()[num]);
                    }
                }

            }
        }

    }

};


function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
    return null;
}